2016-12-17 63 views
1

我在使用Angular2和路由器的特定用例上掙扎了一下。Angular2:在註銷時有條件地重定向到另一個路由

假設我們有3條路線。主頁,列表和配置文件。

「配置文件」是一個有防護的路由:用戶必須通過身份驗證才能訪問此路由。

如果用戶在「配置文件」頁面並註銷,我希望能夠檢測到他不再被允許在當前頁面上,並將其重定向到「主頁」頁面。

但是,如果他在「列表」頁面並註銷,我不想做任何事情(用戶被允許留在這裏,因爲它不是一個守護路線)。

做一個人知道我可以做到這一點,假設我有很多路線,並且我想避免在每個組件中放入這個「用戶允許」邏輯?

回答

3

摘要

在我來說,我喜歡通過檢查令牌我保存到本地存儲的驗證,分給守衛路線我的用戶的訪問。因此,如果我將它們註銷,我將刪除令牌以及當前存儲在本地存儲中的任何數據。您可以在每個路線中使用此功能。

public logout() { 
    localStorage.removeItem('profile'); 
    localStorage.removeItem('access_token'); 
    this.userProfile = undefined; 
    this.router.navigateByUrl('/home'); 
    }; 

我創建一個認證服務。您可以創建兩個不同的服務,或兩個不同的功能。真的,你有很多選擇。這裏有一個選項。

解決方案

要註銷和重新定向,

public logout() { 
    localStorage.removeItem('profile'); 
    localStorage.removeItem('access_token'); 
    this.userProfile = undefined; 
    this.router.navigateByUrl('/home'); 
    }; 

你可以在你的每一個部件使用此功能。或頁面。如果用戶在配置文件頁面上,基本上重定向路由。但是,如果用戶不是頁面或路由需要重定向上然後取出

this.router.navigateByUrl('/home'); 

從功能,使用戶不重定向。

所以你可以有兩個服務

public.service.ts 
    @Injectable() 
export class Public { 
    public logout() { 
     localStorage.removeItem('profile'); 
     localStorage.removeItem('access_token'); 
     this.userProfile = undefined; 
     }; 

然後在你的網頁要註銷用戶,但讓他們在同一頁上使用這項服務

export class SomeComponent { 
     constructor(private router: Router, private public: Public ) { } 
} 

因此,當使用它不會重定向的註銷功能。

然後當用戶註銷時添加這樣的這項服務重定向,

 secure.service.ts 
    @Injectable() 
export class Secure { 
    public logout() { 
     localStorage.removeItem('profile'); 
     localStorage.removeItem('access_token'); 
     this.userProfile = undefined; 
     this.router.navigateByUrl('/home'); 
     }; 

當然你包括服務的任何組件過你叫你html這樣正確的logout function

<a class="myClass" href="#"(click)="public.logout()">Logout</a> 

<a class="myClass" href="#" (click)="secure.logout()">Logout</a> 
+0

嗨wuno,謝謝您的回答。 –

+0

沒問題。這有道理嗎?並幫助? – wuno

+0

事實上,我想出了一些類似的東西,但是爲了避免把邏輯放在每個組件中,如果你有足夠的東西,這可能有點麻煩。我想沒有其他的選擇:/ –