0
votes

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
Could you build a simple blitz to demonstrate your issue? That could help us better understand what is not working for you. Thx. - DeborahK
I see MyComponent used twice in the routing, is that correct? Also, have you tried using this.activatedRoute.snapshot.data? - Vojtech
Yes, the parent and child routes should render the same component. I'm finding that the activatedRoute is returning the parent node instead of the child node at the sub-route - K.F

1 Answers

1
votes

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