AngularM AngularM - 4 months ago 62
Javascript Question

How to detect route change in Angular 2?

I looking to detect route change in my App.ts file.

Once I've done this I will check the global user token to see if they are logged in. Then I can redirect the user if they are not logged in.

Answer

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