Angular router - empty data object for child routes

99封情书 提交于 2019-12-13 03:25:22

问题


My angular router needs to use the same component for both the parent & child route, but pass along data to differentiate between the parent and child routes.

Current issue: the child route does not register any data from the sub-route.

Routing module segment that defines relationship:

{
        path: 'parent-path/:id',
        component: MyComponent,
        children: [{
          path: 'child-path'
          component: MyComponent,
          data: {MY_DATA_KEY: MY_DATA_VALUE},
        }]
},

In the angular component:

constructor(
      //...
      private readonly activatedRoute: ActivatedRoute,
      //...
) {}

ngOnInit() {
   this.activatedRoute.data.subscribe(data => {
      console.log('data', data);  // This prints and empty object //

      /* ... do something with data */
   });
}

Current behaviour:

on hitting route '.../parent-path/some-id'

  • normal expected behaviour, no data present

on hitting route '.../parent-path/some-id/child-path'

  • unexpected behaviour, data is still empty

Note: I also tried adding data at the parent level, which does get registered at both routes. Relatively new to angluar, so any help would be appreciated. Thanks in advance!


回答1:


angular's router is essentially a tree structure with parents and children, data is defined at the nodes in that tree, and the data objects exist at the specific nodes where they're defined. so a parent route will not see a child route data in it's own 'data', nor will the child routes see it's parent 'data' directly. But you can access the parent / child routes from the activated route as needed

this.route.parent.data.subscribe(pd => console.log(pd, 'parent data'));

or

this.route.children.forEach(c => c.data.subscribe(cd => console.log(cd, 'child data'));

here is a stackblitz demonstrating the behavior: https://stackblitz.com/edit/angular-s4mffg?file=src/app/app.module.ts



来源:https://stackoverflow.com/questions/57261752/angular-router-empty-data-object-for-child-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!