【问题标题】:Multiple /Dashboard routes for different Roles With AuthGuard使用 AuthGuard 的不同角色的多个 /Dashboard 路由
【发布时间】:2019-03-05 06:47:56
【问题描述】:

我希望我的主页为不同的角色加载不同的模块

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 路由器不检查下一条路由

或者有没有办法根据路线改变 loadChildren

实际上我想在登录时实现这一点让我们说 如果学生角色已登录,则在路线“仪表板”或“”学生模块上加载 如果已登录培训师角色,则在路线“仪表板”或“”培训师模块上加载 如果管理员角色已登录,则在路由“仪表板”或“”管理模块加载

【问题讨论】:

  • 您可以根据 canActivate 函数内部的条件从 typescript 路由到您的路径。
  • 添加了更多解释,请查看
  • 那么您将在 dashboard 模块 中拥有 3 个 dashboard 组件?就像学生一样,你有一个学生仪表板,管理员 -> 管理员仪表板,教师 -> 教师仪表板。对于 localStorage 中的任何内容,您将路由到该特定仪表板?这是用例吗?

标签: angular angular-routing angular-route-guards


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    当路径匹配并且 angular 认为这是您要求的路径时,这是预期的行为。在您的情况下,似乎唯一可能的选择是在角色更改时更新路由配置。请参阅 router.resetConfig 文档。

    【讨论】:

      猜你喜欢
      • 2016-11-19
      • 2012-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 2021-07-12
      相关资源
      最近更新 更多