Angular 2 router event listener Angular 2 router event listener javascript javascript

Angular 2 router event listener


new router

constructor(router:Router) {  router.events.subscribe(event:Event => {    if(event instanceof NavigationStart) {    }    // NavigationEnd    // NavigationCancel    // NavigationError    // RoutesRecognized  });}

old

Inject the Router and subscribe to route change events

import {Router} from 'angular2/router';class MyComponent {  constructor(router:Router) {    router.subscribe(...)  }}

NOTE

For the new router, don't forget to import NavigationStart from router module

import { Router, NavigationStart } from '@angular/router';

because if you don't import it instanceof will not work and an error NavigationStart is not defined will rise.

See also


You can also filter events with filter().

But don't just use filter(e => e is NavigationEnd)

A much better solution is to add a 'type guard' to filter() like this:

 filter((e): e is NavigationEnd => e instanceof NavigationEnd), 

It contains two things:

  • e is NavigationEnd this is the assertion you're defining a function for (this is typescript syntax and is completely stripped out of the transpiled javascript)
  • e instanceof NavigationEnd this is the actual runtime code that checks the type

The nice thing with this is that operators further down 'the pipe', like map below now know the type is NavigationEnd, but without the type-guard you'd have a type Event.

If you only need to check for one event type then this is the cleanest way to do so. This also appears to be necessary in strict mode to avoid compiler errors.

enter image description here


You can use instanceof as @GünterZöchbauer answered

this.router.events.subscribe(event => {  if(event instanceof NavigationStart) {    // do something...  }}

or you can use a lazier approach, but remember constructor name can be changed easily while the function is still working!

this.router.events.subscribe(event => {  if(event.constructor.name === "NavigationStart") {    // do something...  }});