在新路由器上使用订阅功能时出现 Angular 2 打字稿错误 (rc 1) [英] Angular 2 typescript error when using subscribe function on new router (rc 1)

查看:35
本文介绍了在新路由器上使用订阅功能时出现 Angular 2 打字稿错误 (rc 1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用新路由器为我的 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

(app.component.ts(47,22): 错误 TS2339: 类型 'Router' 上不存在属性 'subscribe'.

(app.component.ts(47,22): error TS2339: Property 'subscribe' does not exist on type 'Router'.

这很奇怪,因为文档 清楚地表明 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
  })
}

原创

Router 类有一个 EventEmitter changes 你可以订阅:

The Router class has an EventEmitter changes you can subscribe to:

ngOnInit(){
  this._router.changes.subscribe(
    next => {
      if (!userIsLoggedInOrWhatever) {
        this._router.navigate(['Login']);
      }
    }
  )    
}

关于如何获取之前的路由,请参见How检测 Angular 2 中的路线变化? (pairwise())

For how to get the previous route see How to detect a route change in Angular 2? (pairwise())

这篇关于在新路由器上使用订阅功能时出现 Angular 2 打字稿错误 (rc 1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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