我曾在一款应用上实现过类似的功能,以下是我的处理方式。
我创建了一个认证服务,其中包含了一个方法,用于检查用户是否有管理角色:
auth.service.ts
public isManager(): boolean {
let isManager = false;
let user = this.getUserToken();
let allowedGroups = AuthenticationParams.filters.split(',');
let userGroups: any;
if (user !== null && user !== undefined) {
try {
let userGroups: any = user.role;
if (userGroups !== undefined && userGroups !== null && userGroups.length > 0) {
try {
userGroups.forEach((e: any) => {
if (allowedGroups.indexOf(e) > -1) {
isManager = true;
}
});
} catch (e) {
if (allowedGroups.indexOf(userGroups) > -1) {
isManager = true;
}
}
}
} catch (e) {
isManager = false;
}
}
return isManager;
}
public getUserToken(): any {
return localStorage.getItem('jwtTokenName');
}
我创建了一个身份验证守卫,代码如下:
guard.component.ts
import { Injectable, OnInit } from '@angular/core';
import { CanActivate, CanActivateChild } from '@angular/router';
import { Router } from '@angular/router';
import { AuthenticationService } from '../services/helper/security/auth.service';
@Injectable()
export class GuardComponent implements CanActivate {
constructor(private authenticationService: AuthenticationService, private _router: Router) {
}
canActivate() {
let isManager: boolean = this.authenticationService.isManager();
if (!isManager) {
this._router.navigate(['unauthorized']);
}
return isManager;
}
}
guard.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { GuardComponent } from './guard.component';
@NgModule({
declarations: [],
imports: [ CommonModule ],
exports: [],
providers: [ GuardComponent ],
})
export class GuardModule { }
我使用了用于管理到管理员区域导航的路由守卫。
app-routing.module.ts
{ path: 'management', component: AdminComponent, canActivate: [GuardComponent] }
在我的导航栏中,我只调用isManager
方法并将其存储在一个变量中,然后使用该变量来确定是否需要显示管理链接。
navbar.component.ts
public isManager: boolean = false;
ngOnInit(): void {
this.isManager = this.authenticationService.isManager();
}
导航栏组件.html
<li [routerLinkActive]="['active']" *ngIf="isManager"><a [routerLink]="['management']">Management Portal</a></li>
我不得不从每个方法中删除一些数据,但这会给你一个基本的想法。希望这可以帮助到你。