我想基于同一(“”)路径(home)上的用户角色加载特定的角度模块。比方说,我有两个名为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;
}
}
不知怎的,它停止照顾第一条路线失败,我做错了什么?
Stackjlitz的例子是djerid: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;
}
}
最好是使用UrlMatchers代替canLoad,根据你的条件匹配每一个,当2路径中的一个匹配时,另一个路径将自动被忽略
const routes: Routes = [{
path: '',
matcher: adminMatcher,
oadChildren: () => AdminModule,
data: { role: 'ADMIN' }
},
{
path: '',
matcher: operatormatcher,
loadChildren: () => OperatorModule,
data: { role: 'OPERATOR' }
}]
检查这个example