在我的Angular 4項目中,我想使用API獲得的權限。權限被保存爲帶有ID的數組。像用戶或博客文章這樣的單個元素具有帶有權限的屬性,這些權限允許或不允許像編輯或刪除操作那樣操作爲具有ID的數組。在Angular 4中使用權限的最佳方式是什麼?
在Angular 4項目中檢查和處理權限的最佳方法是什麼?有角度的權限處理的解決方案的一些解決方案嗎?如果Angular沒有一些開箱即用的解決方案,有人可以給我一些實現權限處理的想法嗎?
在我的Angular 4項目中,我想使用API獲得的權限。權限被保存爲帶有ID的數組。像用戶或博客文章這樣的單個元素具有帶有權限的屬性,這些權限允許或不允許像編輯或刪除操作那樣操作爲具有ID的數組。在Angular 4中使用權限的最佳方式是什麼?
在Angular 4項目中檢查和處理權限的最佳方法是什麼?有角度的權限處理的解決方案的一些解決方案嗎?如果Angular沒有一些開箱即用的解決方案,有人可以給我一些實現權限處理的想法嗎?
像拉胡爾評論說,一個解決方案開箱更可能你想要的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'] }
}
]
}
你可以嘗試使用ngx-permissions庫在你的角度應用程序的權限的控制。它將從DOM中移除元素的好處。裝載權限 例
import { Component, OnInit } from '@angular/core';
import { NgxPermissionsService } from 'ngx-permissions';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
constructor(private permissionsService: NgxPermissionsService,
private http: HttpClient) {}
ngOnInit(): void {
const perm = ["ADMIN", "EDITOR"];
this.permissionsService.loadPermissions(perm);
this.http.get('url').subscribe((permissions) => {
//const perm = ["ADMIN", "EDITOR"]; example of permissions
this.permissionsService.loadPermissions(permissions);
})
}
}
在模板中使用
<ng-template [ngxPermissionsOnly]="['ADMIN']" (permissionsAuthorized)="yourCustomAuthorizedFunction()" (permissionsUnauthorized)="yourCustomAuthorizedFunction()">
<div>You can see this text congrats</div>
</ng-template>
<div *ngxPermissionsOnly="['ADMIN', 'GUEST']">
<div>You can see this text congrats</div>
</div>
<div *ngxPermissionsExcept="['ADMIN', 'JOHNY']">
<div>All will see it except admin and Johny</div>
</div>
這看起來不錯。我會嘗試將其整合到我的項目中。謝謝 –
權限是一樣逆天,你可以在角[逆天]看看看守組件(https://angular.io/api/router/CanActivate)你也可以看看這個[link](https://rahulrsingh09.github.io/AngularConcepts/guard) –