【问题标题】:Angular access routing parameter from parent来自父级的角度访问路由参数
【发布时间】:2020-01-13 08:25:48
【问题描述】:

我有这个路由:

{ 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)

【问题讨论】:

标签: angular


【解决方案1】:

在子组件中,您可以添加以下行。

需要定位父路由快照,因为当前快照就是当前路由,也就是子组件

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));
  }

【讨论】:

  • 有办法订阅吗?我在我的父组件中订阅它:this.route.params.subscribe(params => (this.id = params.id))
  • 在子组件中尝试以下,this.route.parent.params.subscribe(params => (this.id = params.id));
猜你喜欢
  • 2018-02-09
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
  • 2020-08-30
相关资源
最近更新 更多