2016-05-30 56 views
0

對於我在應用程序初始化中訂閱了我的路由器的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

我不清楚問題是什麼。 –

回答

0

我只是說return;應該做你想做的。無論如何,「觸發此代碼的更改」現在已經完成。如果你不明確導航到另一個路徑,這應該是你要求的結果。