3

I have a module with the following routing:

{
    path: '',
    component: PagesComponent,
    children: [
      {
        data: { test: 'snoop' },
        path: 'dashboard',
        loadChildren: './modules/dashboard/dashboard.module#DashboardModule',
      },
      {
        data: { test: 'dogg' },
        path: 'admin', 
        loadChildren: './modules/admin/admin.module#AdminModule' 
      }
    ]
  }

What I'd like to do is pass some data to the PagesComponent component, depending on which lazy loaded module you've loaded.

So, in my PagesComponent I'd like to have something like this:

constructor(private route: ActivatedRoute) {
    this.route.data.subscribe(data => {
      console.log(data);
    });
  }

And the data param will then contain the data defined in the root.

I know I can easily retrieve the data from the routes within the lazy loaded module component itself, but is it possible to get this data in the host component, i.e. PagesComponent?

Background: I'd like to do this so I can display different data in the menu depending on which page you're currently on.

ViqMontana
  • 5,090
  • 3
  • 19
  • 54
  • 1
    Possible duplicate of [How can I access an activated child route's data from the parent route's component?](https://stackoverflow.com/questions/43806188/how-can-i-access-an-activated-child-routes-data-from-the-parent-routes-compone) – Ivan Feb 26 '19 at 13:35
  • @Lends but I'm using lazy loaded modules here. – ViqMontana Feb 26 '19 at 13:38
  • my fault, but the answer is almost the same – Ivan Feb 26 '19 at 13:57

1 Answers1

4

The difference between lazy-loaded and simple routes' data is that you have to look deeper.

constructor(route: ActivatedRoute) {
  route.url.subscribe(() => {
    console.log(route.snapshot.firstChild.firstChild.data);
   });
}
Ivan
  • 1,487
  • 1
  • 16
  • 27