我正在尝试使用新路由器为我的Angular 2应用设置身份验证。有人建议尝试以下方法:
constructor (private _router: Router) {}
ngOnInit(){
this._router.subscribe(
next => {
if (!userIsLoggedInOrWhatever) {
this._router.navigate(['Login']);
}
}
)
}
但是,此问题是导致打字稿错误
(app.component.ts(47,22):错误TS2339:类型“路由器”上不存在属性“订阅”。
这很奇怪,因为文档清楚地表明Router对象确实具有此功能。我可以调用其他功能,例如router.navigate(['/ url'])。你们有什么想法吗?
新路由器
constructor(router:Router) {
router.events.subscribe(event:Event => {
if(event instanceof NavigationStart) {
}
// NavigationEnd
// NavigationCancel
// NavigationError
// RoutesRecognized
})
}
原版的
该Router
课程有一个EventEmitter
changes
您可以订阅的:
ngOnInit(){
this._router.changes.subscribe(
next => {
if (!userIsLoggedInOrWhatever) {
this._router.navigate(['Login']);
}
}
)
}
有关如何获取上一条路线的信息,请参阅如何在Angular 2中检测路线变化?(pairwise()
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句