Search code examples
angularangular-router

getting route custom data when route changes


I'm writing an angular 12 component of a breadcrumb component, i know there are a lot out there, i'm trying to learn something here so go with it :)

so I'm trying to detect route change including the first route when the user opens the website, and I also need to add a custom data that I added to the route.

which means I have

      { path: '', component: HomeComponent, data: {breadcrumb: 'home'}}

as one of my routers, when user browses to the main page I will get an object with {breadcrumb: 'home'}

so in the constructor of my component I have the following:

 constructor(
    private route: ActivatedRoute,
    private router: Router) {
    this.router.events.subscribe((event) => {
    
             if (event instanceof NavigationEnd) {
              const data = this.route.root.snapshot.data;
              const url = event.url;
              console.info('data =>' + JSON.stringify(data));
        ...

the data object is always empty, I googled and there are a lot of answers probably related to previous versions of angular that confused me and didn't really do anything.

for example I read somewhere that I need to check the event RoutesRecognized and there I can get the data, so I added

     if (event instanceof RoutesRecognized) {
         let route = event.state.root.firstChild!.data;
         console.info(route);
         console.info('RECOGNIZED');
       }

and this event is not fired at all, and I prefer to have all I need in one event.

I noticed that NavigationStart did not fire when i first load the page, only when i move to another route, so I used NavigationEnd, so I do get the url properly i just don't get the custom data.

so all I'm trying to do here is to get the url and custom data on url change. any ideas ?


Solution

  • ok so the solution was simple..

    the first page did not load on ActivationStart because I had initialNavigation set to 'enabled':

    @NgModule({
      imports: [RouterModule.forRoot(routes, {
        initialNavigation: 'enabled',
    })],
    

    i didn't really need that, when I removed that parameter ActivationStart would execute on the first page load.

    and then I have :

     if (event instanceof ActivationStart) {
    
            const data = event.snapshot.data;
            const url = event.snapshot.url;
    

    so i get the data object properly and the url comes as UrlSegment array.

    and I can easily get child route data with:

        const childUrl = event.snapshot.firstChild?.url;
        const childData = event.snapshot.firstChild?.data;