Search code examples
angularangular-router

Angular router - empty data object for child routes


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!


Solution

  • 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