2016-12-17 26 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

事实上,我想出了一些类似的东西,但是为了避免把逻辑放在每个组件中,如果你有足够的东西,这可能有点麻烦。我想没有其他的选择:/ –

相关问题