如何检测Angular中的路线变化? [英] How to detect a route change in Angular?

查看:31
本文介绍了如何检测Angular中的路线变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望检测我的 AppComponent 中的路由变化.

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.

推荐答案

在 Angular 2 中,您可以订阅(Rx 事件)到路由器实例.所以你可以做这样的事情

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

编辑(从 rc.1 开始)

Edit (since rc.1)

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

编辑 2(自 2.0.0 起)

Edit 2 (since 2.0.0)

另见:Router.events 文档

class MyClass {
  constructor(private router: Router) {
    router.events.subscribe((val) => {
        // see also 
        console.log(val instanceof NavigationEnd) 
    });
  }
}

这篇关于如何检测Angular中的路线变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆