您好我已存储以下数据
"permission": {
"1000": "CREATE_DISBMT_WORKFLOW",
"1001": "EDIT_DISBMT_WORKFLOW",
"1002": "EDIT_UPLOAD_PHOTO_DISBMT_WORKFLOW",
"1003": "EDIT_UPLOAD_CONFIRMED_DISBMT_WORKFLOW",
"1004": "EDIT_VERIFIED_DISBMT_WORKFLOW",
"1005": "VIEW_DISBMT_WORKFLOW",
"1006": "DELETE_DISBMT_WORKFLOW"
}
在本地存储中现在我想要创建一个函数,如果在上面的权限对象中它将返回true,则我将传递CREATE_DISBMT_WORKFLOW,否则为
在角度2
中做到这一点的方法是什么这里我的逻辑是如果它返回真实数据将使用* ngIf等显示。
答案 0 :(得分:1)
如果您调整权限数据对象以使权限名称是键而不是权限ID,那么您的权限服务可能就像这样简单:
import { Injectable } from '@angular/core';
@Injectable()
export class PermissionsService {
private permissions: any = {}
constructor() { }
setPermissions(permissions: any) : void {
this.permissions = permissions;
}
canCurrentUser(permission: string) : boolean {
return (permission in this.permissions);
}
}
配置:
let permissions = {
"CREATE_DISBMT_WORKFLOW":"1000",
"EDIT_DISBMT_WORKFLOW":"1001",
"EDIT_UPLOAD_PHOTO_DISBMT_WORKFLOW":"1002",
"EDIT_UPLOAD_CONFIRMED_DISBMT_WORKFLOW":"1003",
"EDIT_VERIFIED_DISBMT_WORKFLOW":"1004",
"VIEW_DISBMT_WORKFLOW":"1005",
"DELETE_DISBMT_WORKFLOW":"1006"
}
this.permissionsService.setPermissions(permissions);
使用:
let hasPermission = this.permissionsService.canCurrentUser("CREATE_DISBMT_WORKFLOW");
但如果您需要保留原始权限数据结构,此canCurrentUser(permission)
函数也可以使用(虽然它的可读性较差):
canCurrentUser(permission: string) {
for (var key in this.permissions) {
if (this.permissions.hasOwnProperty(key) && this.permissions[key] === permission) {
return true;
}
}
return false;
}
答案 1 :(得分:1)
对于angular2应用程序的管理权限和访问控制,您可以使用ng2-permission模块。
将Ng2Permission
导入到您应用的模块中:
import { Ng2Permission } from 'angular2-permission';
@NgModule({
imports: [
Ng2Permission
]
})
您还可以使用PermissionService
管理权限。请看这个链接:Managing permissions。
import { PermissionService } from 'angular2-permission';
//.
//.
//.
constructor(private _permissionService: PermissionService) {
this._permissionService.define(['CREATE_DISBMT_WORKFLOW',
'EDIT_DISBMT_WORKFLOW', 'EDIT_UPLOAD_PHOTO_DISBMT_WORKFLOW',
'EDIT_UPLOAD_CONFIRMED_DISBMT_WORKFLOW', 'EDIT_VERIFIED_DISBMT_WORKFLOW',
'VIEW_DISBMT_WORKFLOW', 'DELETE_DISBMT_WORKFLOW']);
}
该模块还包含两个用于控制视图访问的指令。
例如,如果DELETE_DISBMT_WORKFLOW
已经定义或添加到权限存储中,则会显示删除按钮。
<button type="button" class="btn btn-danger btn-xs" [hasPermission]="['DELETE_DISBMT_WORKFLOW']">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
Delete
</button>
您可以使用Ng2Permission
模块中的PermissionGuard来保护路由。
import { PermissionGuard, IPermissionGuardModel } from 'angular2-permission';
const routes: Routes = [
{
path: 'users',
component: UserListComponent,
canActivate: [PermissionGuard],
data: {
Permission: {
Only: ['GuestUser'],
RedirectTo: '403'
} as IPermissionGuardModel
},
children: []
},
//.
//.
//.