我已将我的 angular2 项目升级为RC5
using angular-cli@webpack
.
我提供的路由如下:
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>
现在它已成功重定向,我可以在浏览器的地址栏中看到参数值。
现在我想知道,如何在 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
});
}
不要忘记导入OnInit
from @angular/core
如果你也需要的话。
N.B :您还可以使用this.route.snapshot.params
同步访问它。
EDITED :
- 清理以避免订阅,因为 NG2 路由器自行管理其订阅。
- 避免使用可能在 HTML 中使用的私有变量,以避免破坏 AOT 编译。
- Cleaned
ROUTER_DIRECTIVES
因为它已被弃用。
- 避免使用字符串文字:params['id'] => params.id
- 如果有的话,使用 TypeScript 输入参数
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)