如何在Angular中检测路线变化? [英] How to detect a route change in Angular?
本文介绍了如何在Angular中检测路线变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要检测我的AppComponent
中的路线更改.
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 the user if he is not logged in.
推荐答案
在Angular 2中,您可以subscribe
(Rx事件)到Router实例.
所以你可以做类似的事情
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*/)
}
}
编辑(自版本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屋!
查看全文