我正在尝试设置具有访问路由所需角色的数组。如果路由角色与用户角色匹配,则授予访问权限。这是由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;
}
}
路线数据始终打印未定义。
我猜想routes数组的嵌套结构有问题,因为如果我在第一条路由中设置了 data ,则该数据将由 FullLayoutComponent 处理,效果很好。但这没有用,因为我需要能够为不同的孩子指定不同的角色。
我尝试了几种变体,例如在AdminModule内部的路由中设置data属性,但是没有运气。总是不确定的。
答案 0 :(得分:0)
我在这里回答自己也是为了帮助别人。
对我有用的解决方案是摆脱FullLayoutComponent和NoLayoutComponent,然后仅使用组件或模块正常处理路由。
const ROUTES: Routes = [
{
path: "",
redirectTo: "dashboard",
pathMatch: "full",
},
{
path: "dashboard",
component: DashboardComponent,
canActivate: [AuthGuard]
},
{
path: "admin",
loadChildren: "./admin/admin.module#AdminModule",
canActivate: [AuthGuard],
data: { roles: [Role.Admin] }
},
{
path: "auth",
loadChildren: "./auth/auth.module#AuthModule"
},
{
path: "404",
loadChildren: "./pages/four-zero-four/four-zero-four.module#FourZeroFourModule"
},
{
path: "**",
redirectTo: "/404"
}
];
使用该路由配置,AuthGuard可以按预期工作,并且我唯一要做的更改就是调整布局以在用户未登录时隐藏侧边栏和标题。