在我的Angular 4项目中,我想使用权限,我从API获得.权限保存为带有ID的数组.某些单个元素(如用户或博客帖子)具有允许权限的属性,允许或不允许编辑或删除等操作作为带有ID的数组.
在Angular 4项目中检查和处理权限的最佳方法是什么? Angular中有一些用于权限处理的bos解决方案吗?如果Angular没有一些开箱即用的解决方案,有人可以给我实现权限处理的想法吗?
像Rahul评论说开箱即用的解决方案更可能是你想要的Guard.
原文链接:https://www.f2er.com/angularjs/240432.html请记住,警卫只适用于ROUTING ..所以只检查用户是否可以访问路线..但不要根据角色或其他任何内容显示组件中的单个元素..因为我建议您使用* ngIf或显示以呈现/显示或不显示某些UI元素…
对于基于角色的一个Guard(不仅如果使用是否是auth)..你可以做类似的事情:
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'] } } ] }