这是我目前正在使用的一个示例,不确定它是否是您正在寻找的。
路线
{
path: 'import',
component: ImportComponent,
canActivate: [AuthGuard, RoleGuard],
data: { roles: new Set([UserRole.admin, UserRole.developer]) },
},
警卫
@Injectable({
providedIn: 'root',
})
export class RoleGuard implements CanActivate {
constructor(private store: Store<AppState>, private location: Location) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.store.select(selectUserRoles).pipe(
debounce((roles) => (roles ? EMPTY : timer(2500))),
map((roles) => {
const permittedRoles = (route.data as RouteData).roles;
if (
roles &&
Array.from(roles.values()).some((role) => permittedRoles.has(role))
) {
return true;
} else {
alert(
`Requires one of the following roles: ${Array.from(permittedRoles)
.map((role) => getRoleName(role))
.join(', ')}`
);
this.location.back();
return false;
}
}),
first()
);
}
}