I am looking to detect a route change in my AppComponent
.
Thereafter I will check the global user token to see if the user is logged in so that I can redirect the user if the user is not logged in.
Steps to detect route change in Angular application Urls. Import Router, Event, NavigationStart, NavigationEnd, NavigationError from '@angular/router'. And inject router in the constructor. Subscribe to the NavigationStart, NavigationEnd, NavigationError events of the router.
We can test routing in Angular by using RouterTestingModule instead of RouterModule to provide our routes. This uses a spy implementation of Location which doesn't trigger a request for a new URL but does let us know the target URL which we can use in our test specs.
The Angular Routers triggers several events starting with when the Navigation starts ( NavigationStart ) and also when the Navigation end ( NavigationEnd ) successfully. It is triggered when the navigation is canceled either by the user ( NavigationCancel ) or due to an error in the navigation ( NavigationError).
ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.
In Angular 2 you can subscribe
(Rx event) to a Router instance. So you can do things like
class MyClass { constructor(private router: Router) { router.subscribe((val) => /*whatever*/) } }
Edit (since rc.1)
class MyClass { constructor(private router: Router) { router.changes.subscribe((val) => /*whatever*/) } }
Edit 2 (since 2.0.0)
see also : Router.events doc
class MyClass { constructor(private router: Router) { router.events.subscribe((val) => { // see also console.log(val instanceof NavigationEnd) }); } }
RxJS 6
router.events.pipe(filter(event => event instanceof NavigationStart))
Thanks to Peilonrayz (see comments below)
new router >= RC.3
import { Router, NavigationStart, NavigationEnd, NavigationError, NavigationCancel, RoutesRecognized } from '@angular/router'; constructor(router:Router) { router.events.forEach((event) => { if(event instanceof NavigationStart) { } // NavigationEnd // NavigationCancel // NavigationError // RoutesRecognized }); }
You can also filter by the given event:
import 'rxjs/add/operator/filter'; constructor(router:Router) { router.events .filter(event => event instanceof NavigationStart) .subscribe((event:NavigationStart) => { // You only receive NavigationStart events }); }
Using the pairwise
operator to get the previous and current event also is an nice idea. https://github.com/angular/angular/issues/11268#issuecomment-244601977
import 'rxjs/add/operator/pairwise'; import { Router } from '@angular/router'; export class AppComponent { constructor(private router: Router) { this.router.events.pairwise().subscribe((event) => { console.log(event); }); }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With