typescript Angular - RouteParams

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33572642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:07:10  来源:igfitidea点击:

Angular - RouteParams

routingtypescriptangular

提问by lux_

I am currently testing Angular Alpha 45, escpecially the Routing, and got problems by implementing routing with parameters. I have created a component for my detail view of one specific entity.

我目前正在测试 Angular Alpha 45,尤其是路由,并且在使用参数实现路由时遇到了问题。我为一个特定实体的详细视图创建了一个组件。

@Component({
    templateUrl: 'app/components/projekt/projekt.detail.html',
    directives: [FORM_DIRECTIVES]
})
export class ProjektDetailComponent {
    id: string;
    constructor(params: RouteParams){
        this.id = params.get('id');
    }   
}

The template is looking like this, just display the parameter "id": <h1>Projekt Details: {{id}}</h1>The RouteConfig looks like this:

模板看起来像这样,只显示参数“id”: <h1>Projekt Details: {{id}}</h1>RouteConfig 看起来像这样:

@RouteConfig([
  { path: '/', component: StartComponent, as:'Start'} ,
  { path: '/projekte', component: ProjektOverviewComponent, as:'Projekte'},
  { path: '/projekte/:id', component: ProjektDetailComponent, as:'ProjektDetail'},
  { path: '/projekte/neu', component: NeuesProjektComponent, as:'ProjektNeu'}    
])

The Link and the RouteConfig, which is displayed above, are like the examples in the angular documentation. <a [router-link]="['/ProjektDetail', {'id': '1'}]" class="btn btn-default">Details</a>

上面显示的 Link 和 RouteConfig 就像 angular 文档中的示例。 <a [router-link]="['/ProjektDetail', {'id': '1'}]" class="btn btn-default">Details</a>

So when I navigate to the detail view (e.g. 127.0.0.1:8080/src/#/projekte/1) I get the following error, which is displayed in the console of my browser(I've tested with Edge, Firefox 42, Chrome 46):

因此,当我导航到详细信息视图(例如 127.0.0.1:8080/src/#/projekte/1)时,我收到以下错误,该错误显示在浏览器的控制台中(我已经使用 Edge、Firefox 42 进行了测试,铬 46):

EXCEPTION: Cannot resolve all parameters for ProjektDetailComponent(?). Make sure they all have valid type or annotations.


    18:25:41.376 EXCEPTION: Cannot resolve all parameters for ProjektDetailComponent(?). Make sure they all have valid type or    annotations.1 angular2.dev.js:21984:9
BrowserDomAdapter</BrowserDomAdapter.prototype.logError() angular2.dev.js:21984
BrowserDomAdapter</BrowserDomAdapter.prototype.logGroup() angular2.dev.js:21995
ExceptionHandler</ExceptionHandler.prototype.call() angular2.dev.js:4426
PlatformRef_</PlatformRef_.prototype._initApp/</<() angular2.dev.js:19685
NgZone</NgZone.prototype._notifyOnError() angular2.dev.js:10746
NgZone</NgZone.prototype._createInnerZone/errorHandling.onError() angular2.dev.js:10654
run() angular2.dev.js:141
NgZone</NgZone.prototype._createInnerZone/<.$run/<() angular2.dev.js:10669
zoneBoundFn() angular2.dev.js:111
lib$es6$promise$$internal$$tryCatch() angular2.dev.js:1507
lib$es6$promise$$internal$$invokeCallback() angular2.dev.js:1519
lib$es6$promise$$internal$$publish() angular2.dev.js:1490
[4]</</</<() angular2.dev.js:219
NgZone</NgZone.prototype._createInnerZone/<.$scheduleMicrotask/</microtask() angular2.dev.js:10701
run() angular2.dev.js:138
NgZone</NgZone.prototype._createInnerZone/<.$run/<() angular2.dev.js:10669
zoneBoundFn() angular2.dev.js:111
lib$es6$promise$asap$$flush() angular2.dev.js:1301

Do you have any suggestions?

你有什么建议吗?

回答by Dennis Smolek

As @EricMartinez mentioned you have to import RouteParams correctly. I was playing with my plunker and was getting the exact same errors.

正如@EricMartinez 提到的,您必须正确导入 RouteParams。我在玩我的 plunker 并且遇到了完全相同的错误。

I realized I was importing from 'angular2/angular2'and needed to import from 'angular2/router'

我意识到我正在导入'angular2/angular2'并且需要从'angular2/router'

Here is a plunker that does exactly what you are looking for but with a "cars" component. Plunker

这是一个 plunker,它完全符合您的要求,但带有“汽车”组件。普朗克

回答by Sandeep Kumar

I also got same problem when injecting my DataService& RouteParamsand had to use @Injectin constructor. Here is what I did.

注入我的DataService&时我也遇到了同样的问题,RouteParams并且不得不@Inject在构造函数中使用。这是我所做的。

import {Component, Inject, View} from 'angular2/angular2';
import {RouteParams} from 'angular2/router';

@Component({
    selector: 'about'
})
@View({
    template: 'This is {{id}} about page {{name}}'
})
export class AboutComponent
{
    name: string = "Sandeep";
    id: number;
    constructor( @Inject(RouteParams) params: RouteParams)
    {
        this.id = +params.get('id');
    }
}

Hope it will help you.

希望它会帮助你。

回答by FelipeDrumond

It does not have to do with the issue you had, but its worth saying that you will face the same problem when migrating to Angular2 RC3 ou higher. The Route has changed completely, so your Component will fail again throwing the same exception.

这与您遇到的问题无关,但值得一提的是,当您迁移到 Angular2 RC3 或更高版本时,您将面临同样的问题。Route 已完全更改,因此您的组件将再次失败并抛出相同的异常。

In RC3 or above you will need to rewrite your routes WITHOUT names and your component will need to import ActivatedRoute from '@angular/router' in order to read your parameters. See:

在 RC3 或更高版本中,您需要重写没有名称的路由,并且您的组件需要从 '@angular/router' 导入 ActivatedRoute 以读取您的参数。看:

constructor(private activatedRoute: ActivatedRoute) {

     this.activatedRoute.params.subscribe(params => {
            this.categoryUrl = params['categoryUrl'];

}

回答by Quy Tang

In case of angular-2.rc3+, you can use this snippet.

angular-2.rc3+ 的情况下,您可以使用此代码段。

post.component.ts

post.component.ts

import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component(
   selector: 'projekte'
)
export class ProjekteComponent {
    private id: string;
    constructor(private route: ActivatedRoute) {
    }

    private sub;
    ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
            this.id = params['id'];
        });
    }
    ngOnDestroy() {
        this.sub.unsubscribe();
    }
}

app.routes.ts

app.routes.ts

export const routes: RouterConfig = [
    { path: 'projekte/:id', component: ProjekteComponent }
];
export const appRouterProviders = [
    provideRouter(routes);
];

main.ts

main.ts

import { bootstrap }    from '@angular/platform-browser-dynamic';

import { AppComponent } from './app.component';
import { appRouterProviders } from './app.routes';

bootstrap(AppComponent, [
    appRouterProviders
]);

Hope this help!

希望这有帮助!