UNPKG

@man-es/ngx-chain-functional-guards

Version:

An Angular guard that executes functional guards in a serial manner, waiting for each one to complete before proceeding to the next.

58 lines (53 loc) 2.21 kB
import { inject, EnvironmentInjector, runInInjectionContext } from '@angular/core'; import { Observable, from, of, concatMap, first, takeWhile, last } from 'rxjs'; /** * Helper to transform value to an Observable * @param value - either a value, a promise or an observable * @returns an observable of the value */ function wrapIntoObservable(value) { if (value instanceof Observable) { return value; } else if (value instanceof Promise) { return from(value); } else { return of(value); } } /** * Chains route configured guards on canActivate or canActivateChild, calling them after each other, waiting for each one before calling the next. * * @param guards The array of guards to process. * @returns The result of the first guard that returns `false` or an instance of a `UrlTree`, otherwise `true`. */ function chainActivationGuards(guards) { return (route, state) => { const injector = inject(EnvironmentInjector); return from(guards).pipe(concatMap(guard => { const guardResult = runInInjectionContext(injector, () => guard(route, state)); return wrapIntoObservable(guardResult).pipe(first()); }), takeWhile(val => val === true, true), last()); }; } /** * Chains route configured guards on canDeactivate, calling them after each other, waiting for each one before calling the next. * * @param guards The array of guards to process. * @returns The result of the first guard that returns `false` or an instance of a `UrlTree`, otherwise `true`. */ function chainDeactivationGuards(guards) { return (component, route, state, nextState) => { const injector = inject(EnvironmentInjector); return from(guards).pipe(concatMap(guard => { const guardResult = runInInjectionContext(injector, () => guard(component, route, state, nextState)); return wrapIntoObservable(guardResult).pipe(first()); }), takeWhile(val => val === true, true), last()); }; } /** * Generated bundle index. Do not edit. */ export { chainActivationGuards, chainDeactivationGuards, wrapIntoObservable }; //# sourceMappingURL=man-es-ngx-chain-functional-guards.mjs.map