就像 Rahul 评论说,开箱即用的解决方案更有可能是您想要的Guard
..
请记住,守卫仅用于路由..因此仅检查用户是否可以访问路由..但不根据角色或其他内容在组件中显示单个元素..为此我建议您使用*ngIf
或显示渲染/显示或不显示某些 UI 元素...
对于一个基于角色的守卫(不仅是使用是否经过身份验证)..您可以执行以下操作:
import { Injectable } from "@angular/core";
import { AuthService, CurrentUserService } from "app/shared/services";
import { Router, RouterStateSnapshot, ActivatedRouteSnapshot, CanActivate } from "@angular/router";
import { AspNetUsersDTO } from "app/shared/models";
import { Observable } from "rxjs/Rx";
@Injectable()
export class RoleGuard implements CanActivate {
constructor(private authService: AuthService,
private _currentUser: CurrentUserService,
private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
if (!this.authService.isLoggedIn()) {
resolve(false);
return;
}
var currentUser: AspNetUsersDTO = new AspNetUsersDTO();
this._currentUser.GetCurrentUser().then((resp) => {
currentUser = resp;
let userRole = currentUser.roles && currentUser.roles.length > 0 ? currentUser.roles[0].toUpperCase() : '';
let roles = route && route.data["roles"] && route.data["roles"].length > 0 ? route.data["roles"].map(xx => xx.toUpperCase()) : null;
if (roles == null || roles.indexOf(userRole) != -1) resolve(true);
else {
resolve(false);
this.router.navigate(['login']);
}
}).catch((err) => {
reject(err);
this.router.navigate(['login']);
});
});
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
if (!this.authService.isLoggedIn()) {
resolve(false);
return;
}
var currentUser: AspNetUsersDTO = new AspNetUsersDTO();
this._currentUser.GetCurrentUser().then((resp) => {
currentUser = resp;
let userRole = currentUser.roles && currentUser.roles.length > 0 ? currentUser.roles[0].toUpperCase() : '';
let roles = route && route.data["roles"] && route.data["roles"].length > 0 ? route.data["roles"].map(xx => xx.toUpperCase()) : null;
if (roles == null || roles.indexOf(userRole) != -1) resolve(true);
else {
resolve(false);
this.router.navigate(['login']);
}
}).catch((err) => {
reject(err);
this.router.navigate(['login']);
});
});
}
}
然后您可以在路由中使用,例如:
{
path: 'awards-team',
component: AwardsTeamComponent,
canActivateChild: [RoleGuard],
children: [
{
path: 'admin',
component: TeamComponentsAdminComponent,
data: { roles: ['super-admin', 'admin', 'utente'] }
},
{
path: 'user',
component: TeamComponentsUserComponent,
data: { roles: ['utente'] }
}
]
}