How to detect a route change in Angular?

前端 未结 22 1587
花落未央
花落未央 2020-11-22 04:40

I am looking to detect a route change in my AppComponent.

Thereafter I will check the global user token to see if he is logged in. Then I can redirect t

22条回答
  •  再見小時候
    2020-11-22 05:23

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

提交回复
热议问题