Search code examples
angularservicebreadcrumbsangular4-router

Angular 4 Router - Hook each router changes


I would like to create a Breadcrumb.

Breadcrumb Wikipedia

And for this, I thought about creating a Service to handle it. But I need to hook each router changes, a method or a class that will be used everytime the router state change.

This challenge have to be resolved without adding a onActivate method in all my components because I have a lot of them.

Great thanks !


Solution

  • Angular 7 made the events into an Observable, so you'll need to use different code to filter for the NavigationEnd event.

    class MyService {
      constructor(public router: Router, logger: Logger) {
        router.events
          .pipe(filter(e => e instanceof RouterEvent))
          .subscribe(e => {
            logger.log(e.id, e.url);
          });
      }
    }
    

    See https://angular.io/api/router/RouterEvent for details.