angular - 使用 AuthGuard 的不同角色的多个 /Dashboard 路由
问题描述
我希望我的主页为不同的角色加载不同的模块
const routes: Routes = [
{
path: 'login',
component: LoginComponent,
},
{ path: '', loadChildren: './dashboard/dashboard.module#DashboardModule', canLoad: [AuthGuard], canActivate: [AuthGuard], },
{
path: '',
loadChildren: './dashboard/dashboard.module#DashboardModule',
canActivate: [true]
},
]
AuthGuard 在这里
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
if (localStorage.getItem('ISTRAINER') === Role.Trainer
&& next.routeConfig.loadChildren === './dashboard/dashboard.module#DashboardModule') {
return true;
}
return false;
}
canLoad(route: Route): boolean {
return false;
}
当 canLoad: [AuthGuard] 返回 false 路由器不检查下一条路由时
或者有没有办法根据 Route 改变 loadChildren
实际上,我想在登录时说,如果学生角色在路线“仪表板”上登录,则在“仪表板”或“”学生模块上加载,或者如果在“仪表板”路线上登录教练角色,则在“”教练模块加载或如果管理员角色已登录,则加载“”管理模块
解决方案
你可以使用来自 angular https://angular.io/api/router/UrlMatcher的 url 匹配器
import { trainerMatcher } from './trainerMatcher'
import { studentMatcher } from './studentMatcher'
{
path : '',
matcher : trainerMatcher,
loadChildren : 'trainerModule',
canLoad : [AuthGuard]
},
{
path : '',
matcher : studentMatcher,
loadChildren : 'studentModule'
}
像这样,您可以编写一个匹配器并在那里检查正确的角色。如果您仍然想确保无法加载模块,您可以设置防护。
我自己也遇到过这个问题,发现那篇文章很有帮助: https ://medium.com/@lenseg1/loading-different-angular-modules-or-components-on-routes-with-same-path-2bb9ba4b6566
推荐阅读
- ibm-cloud - 网络带宽 IBM SOFTLAYER CLOUD
- php - Symfony4 有什么方法可以获取我的域名?
- ios - 如何使用 Unity 打开 iPhone 设置?
- idl-programming-language - 如何在 IDL 中将数组存储在数组中?
- angular - mat-select:以编程方式预选项目
- powershell - 无法使用 PowerShell 将多个值附加到 Excel 中的单元格
- spring-cloud-stream - Spring Cloud Stream 主题分区 KStream 读/写
- mysql - Bash 脚本 MySQL 连接和通过变量查询
- sas - 使用 DATE9 格式将数字转换为 SAS 日期
- gremlin - Gremlin:使用顶点变量通过 HTTP 向图形添加边