1. 没有权限内的页面,自动跳转到“无法找到页面”
2. 没有权限的按钮,控件不显示
3. 没有登录token访问需要登录的页面,自动跳转到“无法找到页面”
思路:用一个service 去存储登录用户的权限列表。 在需要权限控制的按钮、控件上通过 *ngIf 控制控件可见性。在每个页面 active 之前去判断权限,并实现没有权限跳转至‘无法找到页面’
- 创建一个permission.service.ts
主要功能:将 “permission1, permssion2, permission3, permission4” 的permission 字符串转化成一个Json 对象:{permission1:true, permission2:true, permission3:true, permission4:true}
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class PermissionsService {
public Items: any;
constructor() {
if (!this.Items) {
//get permission string from storage
let permissionString = window.sessionStorage.getItem('permission');
if (permissionString) {
//parse permission array
this.convertPermissionToJsonStr(permissionString.toLowerCase().split(','));
}
}
}
setStorage_permission(permissionString) {
window.sessionStorage.setItem('permission', permissionString);
//parse permission array
this.convertPermissionToJsonStr(permissionString.toLowerCase().split(','));
}
getStorage_permission() {
return window.sessionStorage.getItem('permission');
}
//convert permission string to jason properties
private convertPermissionToJsonStr(permArray) {
let jsonArray = new Array();
if (permArray && permArray.length>0) {
permArray.forEach(x => {
jsonArray.push('"' + x + '"' + ":true");
});
this.Items = JSON.parse("{" + jsonArray.toString() + "}");
}
}
}
|
- 在需要添加权限的 component 中添加 service 引用
- 在 HTML 中, 通过permission 对象去判断是否有权限。 这个地方 Item 对象包含的 property 就是权限列表中的每个权限名 string.
- 添加一个 auth-guard.service.ts, 用来截取每个页面激活前的判断处理
在页面 activate 之前,去判断:有没有token, 有没有即将激活页面的permission. 如果正常激活 return true, 不激活 return false.
-
import { Injectable } from '@angular/core';import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';import { Observable } from 'rxjs';import { AllService } from '../services/all.service';
@Injectable({providedIn: 'root'})export class AuthGuardService implements CanActivate {
constructor(private all: AllService, private _router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
let permissions = this.all.permission.getStorage_permission();let localRouter = next.url[0].path.trim();let s = this.getPermissionByUrl(localRouter);
if (localRouter != 'charityAllInOne') {this.all.share.SetCharityStep({ Step: -1 });}
let token = this.all.cache.getStorage_userToken();
//no tokenif (token == null) {// navigate to login pagethis._router.navigate(['/login']);// you can save redirect url so after authing we can move them back to the page they requestedreturn false;}
//has user permissionif (permissions != null) {let permArray = permissions.toLowerCase().split(',');let match = permArray.find(x => x == s);if (match != undefined) //need has url permission{return true;}}
//page no permissionthis._router.navigate(['/pageNotFound']);// you can save redirect url so after authing we can move them back to the page they requestedreturn false;
}
}