摘要
在我来说,我喜欢通过检查令牌我保存到本地存储的验证,分给守卫路线我的用户的访问。因此,如果我将它们注销,我将删除令牌以及当前存储在本地存储中的任何数据。您可以在每个路线中使用此功能。
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>
嗨wuno,谢谢您的回答。 –
没问题。这有道理吗?并帮助? – wuno
事实上,我想出了一些类似的东西,但是为了避免把逻辑放在每个组件中,如果你有足够的东西,这可能有点麻烦。我想没有其他的选择:/ –