Angular 4 Router - Hook each router changes

4.2k views Asked by At

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 !

2

There are 2 answers

0
saluce On BEST ANSWER

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.

0
taras-d On

You can use Router events to track route changes

import { Router, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/filter';

class MyService {

  constructor(private router: Router) {
    this.router.events
      .filter(e => e instanceof NavigationEnd)
      .subscribe(e => console.log('Route changed: ' + e.url);

  }

}