问题描述
我正在尝试使用新路由器为我的Angular 2应用设置身份验证。有人建议尝试以下方法:
I am trying to set up authentication for my Angular 2 app with the new router. Someone suggested to try the following:
constructor (private _router: Router) {}
ngOnInit(){
this._router.subscribe(
next => {
if (!userIsLoggedInOrWhatever) {
this._router.navigate(['Login']);
}
}
)
}
然而这个问题是这导致打字稿错误
This problem however is that this results in the typescript error
这很奇怪,因为清楚地显示了一个Router对象确实有这个功能。我可以调用其他函数比如router.navigate(['/ url'])。你们知道这可能是什么问题吗?
This is strange because the documentation clearly shows that a Router object does have this function. I am able to call other functions like router.navigate(['/url']). Do you guys have an idea what could be the problem?
推荐答案
新路由器
constructor(router:Router) {
router.events.subscribe(event:Event => {
if(event instanceof NavigationStart) {
}
// NavigationEnd
// NavigationCancel
// NavigationError
// RoutesRecognized
})
}
原始
路由器
类有一个 EventEmitter
更改
您可以订阅:
The Router
class has an EventEmitter
changes
you can subscribe to:
ngOnInit(){
this._router.changes.subscribe(
next => {
if (!userIsLoggedInOrWhatever) {
this._router.navigate(['Login']);
}
}
)
}
关于如何获取上一条路线,请参阅( pairwise()
)
For how to get the previous route see How to detect a route change in Angular 2? (pairwise()
)
这篇关于在新路由器上使用订阅功能时出现Angular 2 typescript错误(rc 1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!