Angular2 RouteParams没有得到参数

时间:2016-06-27 03:31:13

标签: angular angular2-routing

我遇到了从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,其中cssmelbournenameId。当我点击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'];但没有成功。

1 个答案:

答案 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);
  }
}