41 lines
1.5 KiB
TypeScript
41 lines
1.5 KiB
TypeScript
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
|
|
import { Injectable, InjectionToken, Injector } from '@angular/core';
|
|
import { from, of } from 'rxjs';
|
|
import { LoadingService } from '../loading';
|
|
|
|
@Injectable({
|
|
providedIn: 'root',
|
|
})
|
|
export class CompositeRouteGuard implements CanActivate {
|
|
constructor(protected readonly _injector: Injector, private readonly _loadingService: LoadingService) {}
|
|
|
|
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
|
|
this._loadingService.start();
|
|
|
|
const routeGuards = <InjectionToken<CanActivate>[]>route.data.routeGuards;
|
|
|
|
if (routeGuards) {
|
|
for (let i = 0; i < routeGuards.length; i++) {
|
|
const routeGuard = this._injector.get<CanActivate>(routeGuards[i]);
|
|
let canActivateResult = routeGuard.canActivate(route, state);
|
|
if (canActivateResult instanceof Promise) {
|
|
canActivateResult = from(canActivateResult);
|
|
}
|
|
if (typeof canActivateResult === 'boolean' || canActivateResult instanceof UrlTree) {
|
|
canActivateResult = of(canActivateResult);
|
|
}
|
|
|
|
const result = await canActivateResult.toPromise();
|
|
if (!result) {
|
|
this._loadingService.stop();
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
|
|
this._loadingService.stop();
|
|
|
|
return true;
|
|
}
|
|
}
|