Search code examples
angularroutesangular2-routing

How to detect a route change in Angular?


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.


Solution

  • 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*/)
      }
    }
    

    Since rc.1:

    class MyClass {
      constructor(private router: Router) {
        router.changes.subscribe((val) => /*whatever*/)
      }
    }
    

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