我遇到了从Angular2中的路由获取参数的问题。在app.component.ts
我定义@RouterConfig
:
@RouteConfig([
...
{ path: '/companies', component: CompaniesListComponent, name: 'Companies' },
{ path: '/events/:nameId', component: EventsListComponent, name: 'Events'}
])
在CompaniesListComponent
的模板内,我有以下[routerLink]
:
<a [routerLink]="['/Events', { 'nameId': company.nameId }]" class="btn btn-success col-md-offset-4">Show Events</a>
当我将鼠标悬停在上面的链接上时,它清楚地向我显示company.nameId
设置正确且网址如下:/events/cssmelbourne
,其中cssmelbourne
为nameId
。当我点击EventsListComponent
时未加载的nameId is not defined
链接时。我试图通过以下方式获取nameId
参数:
nameId: string = "";
constructor(private routeParams: RouteParams, private http: Http) {
this.nameId = routeParams.get('nameId');
}
我也试过使用this.nameId = routeParams.params['nameId'];
但没有成功。
答案 0 :(得分:0)
最终错误发生在EventsListComponent
console.log
声明中。我忘了把this.
放在变量之前。所以,在以下之前:
export class EventsListComponent {
nameId: string = "";
constructor(private routeParams: RouteParams, private http: Http) {
this.nameId = routeParams.params['nameId'];
console.log("nameId: " + nameId);
}
}
但它应该是:
export class EventsListComponent {
nameId: string = "";
constructor(private routeParams: RouteParams, private http: Http) {
this.nameId = routeParams.params['nameId'];
console.log("nameId: " + this.nameId);
}
}