27

I see these new events in the new Angular 2 Router.

Theres NavigationStart, NavigationEnd, NavigationFailed (or something like that)

Does anyone know how to use these yet? I've messed around with a few things but haven't been able to get them to do anything.

3 Answers 3

57

The Router provides an events observable that can be subscribed to

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

See also

NOTE

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.

Sign up to request clarification or add additional context in comments.

9 Comments

I see this error with RC4, Unhandled Promise rejection: (SystemJS) Error: Cannot resolve all parameters for 'Router'(?, ?, ?, ?, ?, ?, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'Router' is decorated with Injectable. I handled it with ROUER_PROVIDERS with RC2, but don't know how with RC4 because couldn't find it with RC4. any hint or plunker you have?
This doesn't seem to be related to this question or my answer. See stackoverflow.com/a/38555016/217408
When using this, you may also need to import "Event" from @angular/router. Otherwise, TypeScript will use regular window.Event, which NavigationStart will not resolve to.
Are you putting this in the AppModule constructor?
@oooyaya - I imported Event from @angular/router,but I get compile error. I had to remove it from @angular/router and just do router.events.subscribe(event => { ... }) for it to work (i.e., change event:Event to event).
|
8

Just like this

 constructor( private router:Router ){} this.router.events .filter(event=> event instanceof NavigationStart) .subscribe((event:NavigationStart)=>{ // TODO }); 

3 Comments

Property 'filter' does not exist on type 'Observable<Event>'.
You need to import the filter operator, otherwise you will get this error. import 'rxjs/add/operator/filter'
filter no longer exist on Observable as of rxjs 7.
0

In order for this to work, you need to add .pipe()

this.router.events .pipe(filter((event) => event instanceof NavigationStart)) .subscribe((event: NavigationStart) => { // YOUR code }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.