你只需要爲角色authguards,然後通過他們在canActivate陣列中的路由器
例如。我在我的應用程序中擁有Admin和Judge角色。所以,我有法官後衛:
import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService} from './auth.service';
import {tap, map, take} from 'rxjs/operators';
@Injectable()
export class JudgeGuard implements CanActivate {
constructor(private auth: AuthService, public router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.auth.user.pipe(
take(1),
map(user => !!(user && user.roles.judge)), // if user exists and has role -> true nor false
tap(isJudge => {
if (!isJudge) {
console.log('Acces denied - Judges Only');
this.router.navigate(['/']);
}
})
);
}
}
,然後在路由器模塊,
const routes: Routes = [
...
{path: 'judge-dashboard', component: JudgeDashboardComponent, canActivate: [AuthGuard, JudgeGuard]},