如何获取:来自Angular2中父组件的子路由的id参数

Fer*_*tiz 21 routes angular route-parameters

我试图得到:id param定义

RouterModule.forRoot([
  {
    path: 'orders',
    component: ListComponent,
    children: [
      {
        path: 'view/:id',
        component: ViewComponent
      },
    ]
  }
])
Run Code Online (Sandbox Code Playgroud)

来自ListComponent.

我已经尝试过:

route: ActivatedRoute

route.params.subscribe(params => {
  let id = +params['id'];
})
Run Code Online (Sandbox Code Playgroud)

从ListComponent,但params数组是空的,我想它是因为:id param属于viewComponent而不是listComponent

如何在listComponent中获取id参数?

Gün*_*uer 32

您可以使用该firstChild属性或ActivatedRoute获取子路由:

route.firstChild.snapshot.params['id']
Run Code Online (Sandbox Code Playgroud)

  • 我使用route.snapshot.firstChild,而不是route.firstChild.snapshot还检查firstChild是否已经定义 (3认同)

Fer*_*tiz 12

为了在父组件中获取子进程,我使用了ActivatedRoute的firstChild属性,因为我只在子路由上

route: ActivatedRoute

route.firstChild.params.subscribe(params => {
  let id = +params['id'];
});
Run Code Online (Sandbox Code Playgroud)

  • 唯一正确的答案,因为事情永远不会在Angular中同步发生,这个答案也涵盖了订阅(异步)部分. (3认同)