[英]how to get route parameters in angular2 RC5
我使用angular-cli@webpack
將angular2項目升級到RC5
。
我提供如下路由:
const appRoutes: Routes = [
{ path: 'project-manager', component: ProjectManagerComponent },
{ path: 'designer/:id', component:DesignerComponent } ,
{path: '',redirectTo: '/project-manager',pathMatch: 'full'}
];
我使用routerLink重定向到設計器組件:
<a [routerLink]="['/designer', page._id]"><i class="fa fa-eye fa-fw"></i></a>
現在它被重定向成功,我能夠在瀏覽器的地址欄中看到param值。
現在我想知道,如何在angular2 RC5中的DesignerComponent中訪問此參數。
我相信您需要使用路由器中的ActivatedRoute來操作您的參數。
import { ActivatedRoute } from '@angular/router';
...
constructor(private route: ActivatedRoute, ...) {
}
// TODO :: Add type
value: any; // -> wanted parameter (use your object type)
ngOnInit() {
// get URL parameters
this.route.params.subscribe(params => {
this.value = params.id; // --> Name must match wanted parameter
});
}
如果您需要,也不要忘記從@angular/core
導入OnInit
。
注意:您也可以使用this.route.snapshot.params
同步訪問它。
編輯:
ROUTER_DIRECTIVES
因為它已被棄用。 首先從@angular/router
導入ActivatedRoute
。
import { ActivatedRoute } from '@angular/router';
訪問它的構造函數如下:
constructor(private route: ActivatedRoute){
}
在ngOnInit中訂閱params更改如下:
ngOnInit() {
this.route.params.subscribe(params => {
if (params['id']) {
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.