我有一個angular2應用程序,我實現了註冊和登錄模塊。登錄時收到用戶角色和其他詳細信息。根據用戶的角色,不知道如何正確管理訪問。在Angular2中實現基於角色的訪問
目前我希望使用Angular2服務來分享整個應用程序中的用戶角色和其他詳細信息,並根據角色使用「if」條件來管理訪問。
請提供有關如何正確執行此操作的任何信息。
我有一個angular2應用程序,我實現了註冊和登錄模塊。登錄時收到用戶角色和其他詳細信息。根據用戶的角色,不知道如何正確管理訪問。在Angular2中實現基於角色的訪問
目前我希望使用Angular2服務來分享整個應用程序中的用戶角色和其他詳細信息,並根據角色使用「if」條件來管理訪問。
請提供有關如何正確執行此操作的任何信息。
我會通過構建出一個對象從當用戶成功登錄讀取方式這一點。
// when user logs in build out permissions object
permissions = {
dashboardOne: true,
dashboardTwo: true
}
那麼你的身份驗證服務中,有一個返回根據用戶的權限
一個布爾函數userHasAccess = (() =>{
return {
toDashboardOne:() => {
return this.permissions.hasOwnProperty('dashboardOne');
},
toDashboardTwo:() => {
return this.permissions.hasOwnProperty('dashboardTwo');
}
}
})();
現在整個應用程序可以調用上面的函數
if(this._authService.userHasAccess.toDashboardOne()){
// do something
}
我希望這可以幫助你開始。歡呼聲
您可以嘗試使用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 {
NgxRolesService
.addRole('ROLE_NAME', ['permissionNameA', 'permissionNameB'])
NgxRolesService.addRole('Guest',() => {
return this.sessionService.checkSession().toPromise();
});
NgxRolesService.addRole('Guest',() => {
return true;
});
}
}
模板
<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>
更多信息,請參閱使用wiki page
我看到它是由您執行的。我會檢查一下。 – Harshakj89
是。我可以用這個作爲開始。 – Harshakj89
https://stackoverflow.com/a/44640425/7176268另一種可能的方式來做到這一點。該方法更具動態性,但我更喜歡上述方法,因爲IDE將列出可用選項。 – LLai