angular - 在注销时为当前路由激活 authguard (Angular)
问题描述
我的 Angular 应用程序有两条带有路线守卫的路线
const routes: Routes = [
{path: '', component: MenuComponent},
{path: 'tableChartGFS', canActivate:[AuthGuard] ,component: TableDataChartGfsComponent},
{path: 'tableAccount', canActivate:[AuthGuard] ,component: TableDataAccountComponent},
{path: 'auth', component: AuthComponent}
];
路由守卫检查用户当前是否登录(通过检查用户 BehaviorSubject 当前是否为空或设置为用户实例)
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| boolean
| UrlTree
| Promise<boolean | UrlTree>
| Observable<boolean | UrlTree> {
return this.authService.user.pipe(
map((user) => {
const isAuth = !!user;
if (isAuth) {
return true;
}
return this.router.createUrlTree(['/auth']);
})
);
}
}
当我登录并转到 /tableAccount 路由,然后单击“注销”(将用户 BehaviorSubject 设置为 null)时,我想重定向到主 MenuComponent,因为我不再被允许在此路由上。我怎样才能做到这一点?
解决方案
我通常有一个注销功能来处理注销逻辑,并传递依赖项(路由器、烤面包机、服务等......)像这样的东西
function logout(router: Router, userSrv: userService) {
router.navigateByUrl('auth');
userSrv.user.next(undefined);
}
推荐阅读
- android-studio - android studio 和插件升级到 4.2.2 后,classpath 应该使用哪个 Gradle 版本?
- javascript - 使用扩展名或其他方式在无名函数中编辑变量
- python - 如何从 Google 新闻中抓取图片?
- c# - 将 response.content 保存为 PDF (C#)
- python - 在 Pandas 中估算缺失的时间戳索引?
- react-dropzone - 必须单击 dropzone 两次才能显示文件查看器
- docker - 从 Docker (ksqlDB) 连接到主机上的 Kafka
- java - JUnit assertEquals 失败显示以 [] 结尾的相同字符串
- regex - 如果字符仅在特定位置出现特定次数,如何匹配正则表达式
- reactjs - 如何在antd的表格行中添加data-testid?