2017-03-18 126 views
3

當用戶沒有登錄我的應用程序時,它等於localStorage中不存在'userToken',那麼我只想將他重定向到登錄路由。無法取消當前導航並從根組件導航到其他地方

假設用戶輸入路由/customers,那麼當本地存儲中不存在userToken時,他應該被重定向到登錄屏幕。

App.component.ts

export class AppComponent 
{ 
    constructor(private routerService: RouterService, private router: Router, private authService: AuthenticationService) 
    { 
    if (!authService.isLoggedIn()) 
    { 
     this.router.navigate(['/login']); 
    } 
    } 
} 

路由器導航方法被調用,但它沒有導航到登錄界面,爲什麼不呢?後端的客戶數據試圖獲取,但我在服務器響應中獲得了401。這意味着...根應用程序組件繼續運行之後的代碼。

+0

你應該在導航之前移除令牌叫我想?會有曲線重定向可能是 –

+0

而你在根組件中執行它不正確,它將只執行一次,因爲該應用程序被加載使用canActivate這個https://angular.io/docs/ts/latest/api/router /index/CanActivate-interface.html –

+0

好吧,但是當我訂閱路由應用程序組件中的更改時,它應該可以正常工作。我只是嘗試一下! – Pascal

回答

1

到角2檢查用戶最好的辦法是登錄或沒有之前經歷route.you可以在航線使用「canActivate」這樣定義

{ path: 'customers', component: AppComponent, canActivate: [AuthService] } 

現在在AuthService你可以定義方法

canActivate() { 
     //you can check token is exists or not here 
     if (localstorage.getItem('user')) { 
      return true; 
     } else { 
      this.router.navigate(['login']); 
      return false; 
     } 
    } 

更多詳細信息h ttps://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html

+0

我想過這個,但不想把10個激活方法無處不在...而是一個地方更整潔 - 如果它的工作 - – Pascal

+0

你的意思是你想在許多路線中使用? –

+0

我只是想在一個地方做一次isLoggedIn調用,只要路由發生變化。 – Pascal

0

此代碼將無法工作。

if (!authService.isLoggedIn()) 
{ 
    this.router.navigate(['/login']); 
} 

您應該調用服務來預先授權用戶。但是您正在檢查尚未定義的服務狀態。

+0

創建authService實例,沒有問題。 – Pascal

+0

而且這將只會執行一次,因爲應用程序啓動 –

+0

,你想說什麼? –