Search code examples
angularangular2-routing

Angular Router Event Name


The Angular(2+) router has an events property that is a rxjs subject.

Once subscribed, you are able to listen for events like:

router.events.subscribe((event: Event) => { console.log(event) });

but the problem is you have no way to obtain the event type since it listens for all events. A hacky solution is you can inspect the constructor name of the event like:

router.events.subscribe((event: Event) => {
  if(event.constructor.name === 'NavigationStart') {
    loadingService.start();
  } else if(event.constructor.name === 'NavigationEnd') {
    loadingService.complete();
    drawerService.destroyAll();
  }
});

I was curious if there was a better way to accomplish this?


Solution

  • Event is only the base class.

    The concrete event values are one of

    • NavigationStart
    • NavigationEnd
    • NavigationCancel
    • NavigationError
    • RoutesRecognized

    You can for example use:

    constructor(router:Router) {
      router.events
        .filter(event => event instanceof NavigationStart)
        .subscribe((event:NavigationStart) => {
          // You only receive NavigationStart events
        });
    

    See also How to detect a route change in Angular 2?