我想基于同一(“”)路径(主页)上的用户角色加载特定的 Angular 模块。假设我有两个模块,名为 AdminModule 和 OperatorModule。如果角色是 ADMIN,那么我想加载 AdminModule,否则加载 OperatorModule。我想用 Angular Guard 存档。
现在app.routing.ts
我添加了以下代码:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './core/guards/auth.guard';
import { AdminModule } from './modules/admin';
import { OperatorModule } from './modules/operator';
const routes: Routes = [
{
path: '',
loadChildren: () => AdminModule,
canLoad: [ AuthGuard ],
data: { role: 'ADMIN' }
},
{
path: '',
loadChildren: () => OperatorModule,
canLoad: [ AuthGuard ],
data: { role: 'OPERATOR' }
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
我已经使用以下代码实现了 AngularGuard,它必须显示 OperatorModule:
import { Injectable } from '@angular/core';
import { CanLoad, Route, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanLoad {
constructor(private router: Router) {}
canLoad(route: Route): Promise<boolean> | boolean {
if (route.data.role === 'OPERATOR') {
return true;
}
return false;
}
}
在第一条路线失败后它以某种方式停止寻找,我做错了什么吗?
djerid 的 StackBlitz 示例:https ://stackblitz.com/edit/angular-vd4oyu?file=app%2Fapp-routing.module.ts
===
Matcher 也不起作用:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './core/guards/auth.guard';
import { AdminModule } from './modules/admin';
import { OperatorModule } from './modules/operator';
const routes: Routes = [
{
loadChildren: () => AdminModule,
matcher: AdminMatcher,
data: { role: 'NO' }
},
{
loadChildren: () => OperatorModule,
matcher: OperatorMatcher,
data: { role: 'OPERATOR' }
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
constructor() {
}
}
import { UrlSegment, UrlSegmentGroup, Route } from '@angular/router';
export function AdminMatcher(segments: UrlSegment[], group: UrlSegmentGroup, route: Route) {
const isPathMatch = segments[0].path === route.path;
if (isPathMatch && route.data.role === 'ADMIN') {
return { consumed: [segments[0]] };
} else {
return null;
}
}
export function OperatorMatcher(segments: UrlSegment[], group: UrlSegmentGroup, route: Route) {
const isPathMatch = segments[0].path === route.path;
if (isPathMatch && route.data.role === 'OPERATOR') {
return { consumed: [segments[0]] };
} else {
return null;
}
}