首页 > 解决方案 > 使用 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

实际上,我想在登录时说,如果学生角色在路线“仪表板”上登录,则在“仪表板”或“”学生模块上加载,或者如果在“仪表板”路线上登录教练角色,则在“”教练模块加载或如果管理员角色已登录,则加载“”管理模块

标签: angularangular-routingangular-route-guards

解决方案


你可以使用来自 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


推荐阅读