angular - Angular 12 - 根据角色重定向用户
问题描述
我有一个场景,管理员角色登录将有权访问 Home 和 UserView 组件。默认情况下,管理员将在登录后转到主页组件。用户角色登录只能访问 UserView 组件,登录后应重定向到 Userview 组件。
我使用过 canactivate 但对如何根据上述条件根据角色重定向用户感到困惑,将有 2 个主页(主页(用于管理员角色)和 UserView(用于用户角色)组件)。
解决方案
在您的情况下,希望您在登录 api 响应中获得用户角色。您需要将用户重定向到他们角色的特定视图库。
login() {
this.authenticationService.login(this.email, this.password).subscribe((response: any) => {
this.authenticationService.getAccountData().subscribe((res: any) => {
this.authority = res.authorities[0]; // role
this.sharedService.setUserRole(this.authority);
if (this.authority === Role.ADMIN_ROLE) {
this.router.navigate(['admin/home']);
} else if (this.authority === Role.USER_ROLE) {
this.router.navigate(['user/home']);
}
});
});
}
要限制路由,您需要创建身份验证防护,您需要在其中实现逻辑以检查请求路由的角色。
import { Injectable } from '@angular/core';
import { Router, NavigationEnd, Route } from '@angular/router';
@Injectable()
export class AdminAuthGuardService {
constructor(
private sharedService: SharedService,
private router: Router
) { }
canActivate(route: Route): boolean {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
if (event.url === '/' || event.url === '/login') {
if (this.sharedService.getRole() === Role.ADMIN_ROLE) {
return true;
} else{
return false;
}
}
}
});
}
}
然后在你的路由文件中使用这个 AdmiAuthGuard
path: 'admin',
canActivate: [AdminAuthGuardService],
children: [
{
path: 'home',
loadChildren: '' // add chile module path
},
]
推荐阅读
- typescript - 一切正常时如何解决 MSBuild Typescript 错误?
- javascript - 表单提交时的 sessionStorage
- ios - PHPickerViewController 点击搜索会出错...“无法加载照片”
- javascript - 如果页面关闭,是否有任何方法可以保存有关打开选项卡的信息?
- python - 触发多页/多选项卡应用程序的子选项卡选择回调
- javascript - 解析 JS 对象以在 PHP 相同文件中处理
- python - 创建一个从 2 到 20 的偶数数组。然后使用 for 循环和 append 函数,将可被 7 整除的 30 到 50 的数字插入该数组
- c++ - 原子布尔向量的线程安全
- javascript - 带有 p5js 画布的 React-Native 应用程序在移动设备上失败
- python - 将视频转换为帧时如何在使用“cv2”时更改每秒帧数(FPS)?