【发布时间】:2019-12-04 07:10:00
【问题描述】:
我正在尝试设置一个具有访问路由所需角色的数组。如果路由角色与用户角色匹配,则授予访问权限。这是由 AuthGuard 完成的。
这是我的路由模块的配置方式:
const ROUTES: Routes = [
{
path: "",
component: FullLayoutComponent,
canActivate: [AuthGuard],
children: [
{
path: "",
redirectTo: "dashboard",
pathMatch: "full",
},
{
path: "dashboard",
loadChildren: "./dashboard/dashboard.module#DashboardModule",
},
{
path: "admin",
loadChildren: "./admin/admin.module#AdminModule",
data: { roles: [Role.Admin] }
}
]
},
{
path: "",
component: NoLayoutComponent,
children: [
{
path: "auth",
loadChildren: "./auth/auth.module#AuthModule"
},
{
path: "**",
redirectTo: "/404"
}
]
}
];
这就是 AuthGuard:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authenticationService: AuthService) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authenticationService.user;
if (currentUser) {
// check if route is restricted by role
console.log("route.data.roles", route.data.roles); // undefined
console.log("route.parent.data.roles", route.parent.data.roles); // undefined
console.log("user.roles", this.authenticationService.user.roles); // ok
if (route.data.roles && !this.authenticationService.userHasRole(route.data.roles)) {
// role not authorised so redirect to home page
this.router.navigate(['/']);
return false;
}
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/auth/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
路线数据总是打印undefined。
我猜路由数组的嵌套结构有问题,因为如果我在第一个路由中设置 data,则由 FullLayoutComponent 处理的路由,它工作正常。但这不起作用,因为我需要能够为不同的孩子指定不同的角色。
我尝试了几种变体,例如在 AdminModule 内部的路由中设置 data 属性,但没有成功。它总是未定义的。
【问题讨论】: