所以我不得不落实我制定了一个应用程序这样的事情,这是我如何处理它。
我创建了一个身份验证服务,这包含在该检查是用户有一个管理角色的方法:我创建了一个权威性后卫如下
auth.service.ts
public isManager(): boolean {
let isManager = false;
let user = this.getUserToken();
//Stored my allowed groups in a config file, comma separated string
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
方法和存储的一个变量,并用它来确定wheth是否需要显示或不显示管理链接。
navbar.component.ts
public isManager: boolean = false;
ngOnInit(): void {
this.isManager = this.authenticationService.isManager();
}
navbar.component.html
<li [routerLinkActive]="['active']" *ngIf="isManager"><a [routerLink]="['management']">Management Portal</a></li>
我不得不从每个方法删除一些数据,但是这会给你基本的想法。希望这有助于。
这个问题是远远这么的Q/A格式过于宽泛。有迹象表明,讨论如何解决这些问题的写的书全章。简而言之:路由,认证守卫和模块。 – axlj
@axlj是的,我明白了。你是对的。但是你怎么知道这么多人现在不喜欢看书。更多对某些问题有好点子的人不会写一本关于它的书。但是,也许如果所有这些人写一些小答案,那么我们将有一个地方,不喜欢读书的人可以阅读这个。并添加他们自己的东西:) –
我听到你,我更喜欢创造阅读长书。不幸的是,对这个特定问题的完整答案会产生这样的结果! – axlj