如何在angular2 RC5中获取路由参数
我已使用如何在angular2 RC5中获取路由参数,angular,typescript,angular2-routing,Angular,Typescript,Angular2 Routing,我已使用angular2将我的angular2项目升级为RC5-cli@webpack 我已提供如下路由: const appRoutes: Routes = [ { path: 'project-manager', component: ProjectManagerComponent }, { path: 'designer/:id', component:DesignerComponent } , {path: '',redirectTo: '/project-m
angular2将我的angular2项目升级为RC5
-cli@webpack
我已提供如下路由:
const appRoutes: Routes = [
{ path: 'project-manager', component: ProjectManagerComponent },
{ path: 'designer/:id', component:DesignerComponent } ,
{path: '',redirectTo: '/project-manager',pathMatch: 'full'}
];
我使用routerLink重定向到designer组件,如下所示:
<a [routerLink]="['/designer', page._id]"><i class="fa fa-eye fa-fw"></i></a>
现在它被成功重定向,我可以在浏览器的地址栏中看到参数值
现在我想知道,如何在angular2 RC5中的DesignerComponent中访问此参数。首先从
@angular/router
导入ActivatedRoute
import { ActivatedRoute } from '@angular/router';
访问it构造函数,如下所示:
constructor(private route: ActivatedRoute){
}
ngOnInit() {
this.route.params.subscribe(params => {
if (params['id']) {
}
});
}
订阅ngOnInit内部的参数更改,如下所示:
constructor(private route: ActivatedRoute){
}
ngOnInit() {
this.route.params.subscribe(params => {
if (params['id']) {
}
});
}
我相信您需要使用来自路由器的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
N.B:您还可以使用this.route.snapshot.params
同步访问它
编辑:
- 清理以避免订阅,因为NG2路由器自己管理其订阅
- 避免使用可能在HTML中使用的私有变量,以避免破坏AOT编译
- 清理了
,因为它已被弃用路由器\u指令
- 避免使用字符串文字:params['id']=>params.id
- 使用TypeScript键入参数(如果有的话)
OnDestroy
事件中取消订阅。这条路线是自己管理的。您实际上可以剪切此.sub
。编辑答案以获得最新信息!