angular - 角基本后卫
问题描述
可以使用角色 args 创建守卫吗?
我想要这样的东西:
{
path: 'app1',
loadChildren: 'src/app/app1/app1.module#App1Module',
canActivate: [new Guard ([Role.Admin, Role.app1])]
}
和激活功能:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const user = this.authenticationService.user;
if (user &&
user.roles &&
user.roles.some((role) => this.roles.includes(role))) {
return true;
}
}
解决方案
我们接下来要做的是,实现两个 Guards AuthGuard(启用 API 身份验证)和 CleanGuard(禁用身份验证)。
现在,在app-routing.module.ts
. 我们可以更灵活地为特定的 API 集启用身份验证,而有些则不启用。
const routes: Routes = [
{ path: 'pages', canActivate: [AuthGuard], loadChildren: 'app/pages/pages.module#PagesModule' },
{
path: 'auth',
component: JGAuthComponent,
canActivate: [CleanGuard],
children: [
{
path: '',
component: LoginComponent,
},
{ path: '', redirectTo: 'pages', pathMatch: 'full' },
{ path: '**', redirectTo: 'pages' },
];
清洁卫士
@Injectable()
export class CleanGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router,
private tokenService: JGTokenService) {
}
canActivate(): Observable<boolean> {
this.tokenService.clear();
return observableOf(true);
}
}
AuthGuard
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router) {
}
canActivate(): Observable<boolean> {
return this.authService.isAuthenticated()
.pipe(
tap(authenticated => {
if (!authenticated) {
this.router.navigate(['auth/login']);
}
}),
catchError((d) => {
this.router.navigate(['auth/login']);
return observableOf(false);
}),
)
}
}
推荐阅读
- r - UpsetR - 选择交叉点进行可视化
- android - Android Java Paho MQTT connect with Google IoT Core attach Google root CA 认证包
- r - 从 R 中的李克特量表数据创建频率表
- r - R循环列出变量的所有值
- python - CGAL Python 3 绑定未正确安装
- amazon-s3 - 何时使用 S3 Presigned Url 与通过后端上传
- javascript - 将局部变量从 Tulind 函数传递给另一个
- angularjs - 使用 EJS 显示斜体文本
- reactjs - 添加 'node_modules/lib-name/dist/some-file-to-declare' 创建 React App 的文件声明
- javascript - 模糊事件在 keydown 上触发