[英]Angular2 router canActivate after logout
我对某些路由使用了登录保护(例如'/profile')。 看起来像这样:
canActivate() {
if (this.user.islogin) return true;
this.router.navigate(['']);
}
如果用户未登录并尝试访问某些路由,它会将用户重定向到主页。 它工作正常。 用户可以从任何页面注销。 我希望我的应用程序具有下一个行为:如果用户在“/profile”页面上并单击“注销”,他应该通过 canActivate() 方法重定向到主页。 但是在这种情况下不会调用此方法。 我应该怎么做才能运行 canActivate()(重新加载页面,手动调用)? 我的注销方法:
logout() {
localStorage.removeItem('auth_token');
this.islogin = false;
}
我试图添加this.router.navigate([this.router.url]);
注销方法,但结果是一样的。 只有当我重新加载页面时,angular2 才会重定向我。 什么是正确的方法?
考虑到您的守卫只使用islogin
并且您在用户注销时将其设置为 false,最简单的方法是在注销时简单地重定向:
logout() {
localStorage.removeItem('auth_token');
this.islogin = false;
this.router.navigate(['']); <---- ADD THIS
}
如果你想在不改变路由的情况下重用canActivate()
的逻辑,你可以这样做:
首先,在您的logout()
所在的任何地方注入服务:
constructor(
private router: Router,
private route: ActivatedRoute,
private canActivateGuard: CanActivateGuard) {}
(只需使用您使用的名称而不是CanActivateGuard
)
接下来,在logout()
调用它:
logout() {
this.canActivateGuard.canActivate(
this.route.snapshot,
this.router.routerState.snapshot);
}
这个问题很老,但问题是当前的。
从 Angular v6 开始,您可以设置路由器的onSameUrlNavigation
属性:
RouterModule.forRoot(routes, {
...
onSameUrlNavigation: 'reload'
})
并在您需要的地方设置runGuardsAndResolvers
:
{
path: '',
component: AccountComponent,
canActivate: [AuthGuard],
runGuardsAndResolvers: 'always'
}
在您的注销方法中,只需调用相同的路由,您的 auth 守卫的canActivate
方法就会被触发:
signout(): void {
this.store.dispatch({
type: AuthActionTypes.Signout
});
// Navigate to the same url to invoke canActivate method
// in routes with runGuardsAndResolvers.
// Also activated onSameUrlNavigation router property.
this.router.navigate([this.auth.redirectUrl]);
}
在上面的示例中, redirectUrl
是保存当前 url 的属性。
虽然是一个老问题,但我遇到了类似的问题,我只是通过使用async 和 await解决了它
我正在使用AngularFireAuth对Angular进行Firebase 身份验证
当我使用以下代码时:
logout(){
this.fbAuthService.fbSignOut();
this.router.navigate(['/login']);
}
用户已正确注销,但this.router.navigate(['/login'])不起作用! 如果我重新加载页面,它会起作用。
后来我怀疑我可能要等待注销过程完成,然后调用this.router.navigate(['/login']) ) 函数。
所以我把它改成:
async logout(){
await this.fbAuthService.fbSignOut();
this.router.navigate(['/login']);
}
它就像一个魅力! 希望它可以帮助可能偶然发现此问题的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.