Angular之ngx-permissions的常見使用情況
權限驗證
首先需要請求驗證并通過,然后獲得權限,最后檢查權限。
這種方式需要在Angular 4.3.2 版本以上才會有效工作。
一般來說我們的程序有2個守衛,一個是信息驗證,一個是權限守衛,并且一定是先請求信息驗證,然后才是權限驗證。
例如下面的路由配置:
let routes = [{ path: '', canActivate: [AuthGuard],children: [{path: 'component', component: ComponentName, canActivate: [NgxPermissionsGuard],data: {permissions: {only: ['ADMIN', 'MODERATOR'],redirectTo: 'another-route'}}}]}
]
守衛過程為,必須先通過 AuthGuard
和 NgxPermissionsGuard
后才能進入下一個路由,上面代碼中為當用戶為ADMIN或者MODERATOR時才能通過。
注意:確保在身份驗證后衛鏈接的權限請求
canActivate() {return authLogin().then((obj) => {// or load here if you dont need second request// this.permissions.service.loadPermissions(obj.permissions)return this.authPermissions.getPermissions('url');}).then((permissions) => {this.permissions.service.loadPermissions(permissions))
}
保存權限
當用戶刷新頁面的所有數據都將丟失,包括該用戶的權限。有很多的保存權限的方式,但是取決于你的業務需求。但最常見的是將它們保存到 localStorage 的。然后從 localStorage 的應用程序啟動時加載它們。
例如下面的代碼:
login() {return authLogin().then((obj) => {// Save permissions to localStorage.localStorage.setItem('permissions', JSON.stringify(obj.permissions));this.permissions.service.loadPermissions(obj.permissions); })
}
禁用元素
通過服務禁用
this.ngxPermissionsConfigurationService.addPermissionStrategy('disable', (templateRef: TemplateRef) => {this.renderer2.setAttribute(tF.elementRef.nativeElement.nextSibling, 'disabled', 'true');// 下面的也可以,但是不推薦。templateRef.elementRef.nativeElement.nextSibling.setAttribute('disabled', true)
});this.ngxPermissionsConfigurationService.addPermissionStrategy('enable', (templateRef: TemplateRef) => {this.renderer2.removeAttribute(tF.elementRef.nativeElement.nextSibling, 'disabled');
});
通過ngxPermissions指令
使用 ngxPermissions指令 配合authorisedStrategy策略。
<button *ngxPermissionsOnly="'ADMIN'; authorisedStrategy: 'enable'; unauthorisedStrategy: 'disable'"><div>Admin will only see this</div>
</button>
也可以通過ngxPermissions指令配合服務來使用:
html
<button *ngxPermissionsOnly="'ADMIN'"><div>This button will be disabled if user has no permissions or role 'admin'</div>
</button>
component
this.ngxPermissionsConfigurationService.setDefaultOnAuthorizedStrategy('enable');orthis.ngxPermissionsConfigurationService.setDefaultOnUnauthorizedStrategy('disable')