订阅新的Angular 2路由器的更改(> = rc1)

订阅新的Angular 2路由器的更改(> = rc1)

问题描述:

对于我在应用程序初始化中订阅了我的路由器的Angular 2应用程序的身份验证。我检查是否设置了用户,如果不是,我尝试从我的登录服务中获取用户,如果这也不可行,我想转到登录页面。订阅新的Angular 2路由器的更改(> = rc1)

ngOnInit() { 
    this._router.changes.subscribe(
     next => { 
      // First check if our component has a user set 
      if (this.loggedInUser === undefined) { 
       // It doesn't, let's set this user with help from our loginService 
       this.loggedInUser = this._loginService.getUser(); 

------->  I think that this is where I need to add a line like: 
     if the user now is logged in, finish the change that triggered this code. 

       // If user stil isn't set, we need to login 
       if (this.loggedInUser === undefined) { 
        // Check if the user isn't already at the login page 
        if (!(this._router.urlTree.contains(this._router.createUrlTree(['login'])))) { 
         console.log('Not authorised, redirected to login.'); 
         this._router.navigate(['login']); 
        } 
       } 
      } 
     } 
    ); 
} 

该解决方案的问题在于我的应用程序中的硬链接不再工作。

例如: 如果我去localhost:8000/user/1我的应用程序被初始化,我的应用程序从我的loginService获取用户。但是,它不会转到我输入的链接,我可以通过菜单导航到此用户。我想我需要添加一行告诉路由器它应该遵循下一个动作?这种结构可能吗?

编辑:我希望问题更清楚,解释如下: 如果我转到某个网址,例如http://aplication/users/5,上面的代码段被触发。大多数情况下,用户已经登录,凭据从loginService中检索。我如何告诉路由器它应该完成触发代码的更改操作?

+0

我不清楚问题是什么。 –

我只是说return;应该做你想做的。无论如何,“触发此代码的更改”现在已经完成。如果你不明确导航到另一个路径,这应该是你要求的结果。