总结
在我的情况下,我喜欢通过检查我保存到本地存储的令牌的验证来让我的用户访问受保护的路由。因此,如果我将它们注销,我会删除令牌以及我当前在本地存储中拥有的任何数据。您可以在每条路线中使用此功能。
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>