Angular 4 Router - Hook each router changes
Asked Answered
L

2

7

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 !

Lepper answered 28/8, 2017 at 10:5 Comment(0)
A
5

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.

Asuncionasunder answered 24/6, 2020 at 13:24 Comment(0)
L
13

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);

  }

}
Lazaro answered 28/8, 2017 at 10:12 Comment(0)
A
5

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.

Asuncionasunder answered 24/6, 2020 at 13:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.