我有此路由:
{ path: 'item/:id',
component: parentComponent,
children: [
{ path: 'edit', component: childComponent }
]
}
要导航到此位置,请使用以下网址:
this.router.navigate(['/item/' + item.id + '/edit']);
现在我的问题是:
现在我的childComponent如何知道ID?我需要什么代码才能在child.component.ts中获取ID? (parentComponent也需要知道ID,这就是为什么我结尾没有Parameter的原因)
答案 0 :(得分:3)
在子组件中,您可以添加以下行。
您需要定位父路由快照,因为当前快照是当前路由,它是子组件
constructor(private route: ActivatedRoute) {
this.id = this.route.parent.snapshot.paramMap.get('id')
console.log('got the id', this.id);
}
或者如果您想在子组件中订阅参数,则可以使用
constructor(private route: ActivatedRoute) {
this.route.parent.params.subscribe(params => console.log('params id', params.id));
}