自测试版以来,我一直在尝试使用Angular 2,现在使用rc.0 +,有些事情发生了变化。
其中一个是无法从@ angular / router导入的RouteParams。当我尝试@ angular / router-deprecated时,我收到一条错误消息:
原始例外:没有RouteParams的提供者!
app.component:
@Routes([
{ path: '/', component: StartComponent },
{path: '/:projId/:userName', component: ProjectListComponent},
{ path: '*', component: StartComponent },
])
项目list.component:
import {Component, OnInit} from '@angular/core';
import {RouteParams} from '@angular/router-deprecated';
@Component({
...
})
export class ProjectListComponent implements OnInit {
userName:string;
projId:string;
constructor(private params:RouteParams) {
this.userName = params.get('userName');
this.projId = params.get('projId');
}
}
从哪里可以导入RouteParams,还是其他我做错了?
谢谢!
答案 0 :(得分:10)
一种方法是
routerOnActivate(curr: RouteSegment) {
this.userName = curr.getParam('userName');
this.projId = curr.getParam('projId');
}
答案 1 :(得分:7)
您必须使用RouteSegment
而不是在angular2 RC中使用RouteParams
。像这样: -
import { Component } from '@angular/core';
import { Routes, RouteSegment, ROUTER_DIRECTIVES } from '@angular/router';
@Component({
selector: 'about-item',
template: `<h3>About Item Id: {{id}}</h3>`
})
class AboutItemComponent {
id: any;
constructor(routeSegment: RouteSegment) {
this.id = routeSegment.getParam('id');
}
}
@Component({
selector: 'app-about',
template: `
<h2>About</h2>
<a [routerLink]="['/about/item', 1]">Item 1</a>
<a [routerLink]="['/about/item', 2]">Item 2</a>
<div class="inner-outlet">
<router-outlet></router-outlet>
</div>
`,
directives: [ROUTER_DIRECTIVES]
})
@Routes([
{ path: '/item/:id', component: AboutItemComponent }
])
export class AboutComponent { }