UNPKG

ngx-serial-route-guards

Version:

Collection of utility functions for executing functional Angular Route Guards serially.

64 lines (59 loc) 2.71 kB
import { inject, EnvironmentInjector, runInInjectionContext } from '@angular/core'; import { EMPTY, from, isObservable, of, concat, takeWhile, last } from 'rxjs'; const wrapIntoObservable = (input) => { if (input === null || input === undefined) { return EMPTY; } if (isPromise(input)) { return from(input); } if (isObservable(input)) { return input; } return of(input); }; const isPromise = (obj) => !!obj && obj instanceof Promise; /** * Runs the CanActivateFn route guards serially. * @param guards Route guards to be run serially. * @returns An observable that resolves to true if all guards are valid. Otherwise it returns the value from the first guard that failed. */ const canActivateSerially = (guards) => (route, state) => { const injector = inject(EnvironmentInjector); const guardResults = []; for (const guard of guards) { guardResults.push(wrapIntoObservable(runInInjectionContext(injector, () => guard(route, state)))); } return concat(...guardResults).pipe(takeWhile((v) => typeof v === 'boolean' && v.valueOf() === true, true), last()); }; /** * Runs the CanMatchFn route guards serially. * @param guards Route guards to be run serially. * @returns An observable that resolves to true if all guards are valid. Otherwise it returns the value from the first guard that failed. */ const canMatchSerially = (guards) => (route, segments) => { const injector = inject(EnvironmentInjector); const guardResults = []; for (const guard of guards) { guardResults.push(wrapIntoObservable(runInInjectionContext(injector, () => guard(route, segments)))); } return concat(...guardResults).pipe(takeWhile((v) => typeof v === 'boolean' && v.valueOf() === true, true), last()); }; /** * Runs the CanDeactivateFn route guards serially. * @param guards Route guards to be run serially. * @returns An observable that resolves to true if all guards are valid. Otherwise it returns the value from the first guard that failed. */ const canDeactivateSerially = (guards) => (component, currentRoute, currentState, nextState) => { const injector = inject(EnvironmentInjector); const guardResults = []; for (const guard of guards) { guardResults.push(wrapIntoObservable(runInInjectionContext(injector, () => guard(component, currentRoute, currentState, nextState)))); } return concat(...guardResults).pipe(takeWhile((v) => typeof v === 'boolean' && v.valueOf() === true, true), last()); }; /** * Generated bundle index. Do not edit. */ export { canActivateSerially, canDeactivateSerially, canMatchSerially }; //# sourceMappingURL=ngx-serial-route-guards.mjs.map