From 2f0e2ac5e7fbf91cbec2399cb2fb069cc03d4e27 Mon Sep 17 00:00:00 2001 From: Shuaib Hasan Akib <48770016+MeAkib@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:03:46 +0600 Subject: [PATCH] fix(router): respect guard order when a guard throws a RedirectCommand Guards in the same array resolve in array order: the first guard that does not return `true` decides the result, even if a later guard finishes first. A guard that threw a `RedirectCommand` skipped this, because the thrown error ended the combined guard result immediately, so its redirect won over an earlier guard that was still running. (cherry picked from commit 21dd0171b39f62ce3f1112f5ca0b9e7cac59af2d) --- .../router/bundle.golden_symbols.json | 1 + packages/router/src/operators/check_guards.ts | 47 ++++--- .../src/operators/prioritized_guard_value.ts | 18 ++- .../router/test/integration/guards.spec.ts | 127 ++++++++++++++++++ 4 files changed, 174 insertions(+), 19 deletions(-) diff --git a/packages/core/test/bundling/router/bundle.golden_symbols.json b/packages/core/test/bundling/router/bundle.golden_symbols.json index 1adbe4d792b..3e9c19be2bb 100644 --- a/packages/core/test/bundling/router/bundle.golden_symbols.json +++ b/packages/core/test/bundling/router/bundle.golden_symbols.json @@ -444,6 +444,7 @@ "bootstrapApplication", "borrowReactiveLViewConsumer", "cacheMatchingLocalNames", + "callGuard", "callHook", "callHookInternal", "callHooks", diff --git a/packages/router/src/operators/check_guards.ts b/packages/router/src/operators/check_guards.ts index 87078db4652..f1f05c8db68 100644 --- a/packages/router/src/operators/check_guards.ts +++ b/packages/router/src/operators/check_guards.ts @@ -217,12 +217,13 @@ function runCanDeactivate( const canDeactivateObservables = canDeactivate.map((c: any) => { const closestInjector = currARS._environmentInjector; const guard = getTokenOrFunctionIdentity(c, closestInjector); - const guardVal = isCanDeactivate(guard) - ? guard.canDeactivate(component, currARS, currRSS, futureRSS) - : runInInjectionContext(closestInjector, () => - (guard as CanDeactivateFn)(component, currARS, currRSS, futureRSS), - ); - return wrapIntoObservable(guardVal).pipe(first()); + return callGuard(() => + isCanDeactivate(guard) + ? guard.canDeactivate(component, currARS, currRSS, futureRSS) + : runInInjectionContext(closestInjector, () => + (guard as CanDeactivateFn)(component, currARS, currRSS, futureRSS), + ), + ).pipe(first()); }); return of(canDeactivateObservables).pipe(prioritizedGuardValue()); } @@ -242,16 +243,29 @@ export function runCanLoadGuards( const canLoadObservables = canLoad.map((injectionToken: any) => { const guard = getTokenOrFunctionIdentity(injectionToken, injector); - const guardVal = isCanLoad(guard) - ? guard.canLoad(route, segments) - : runInInjectionContext(injector, () => (guard as CanLoadFn)(route, segments)); - const obs$ = wrapIntoObservable(guardVal); + const obs$ = callGuard(() => + isCanLoad(guard) + ? guard.canLoad(route, segments) + : runInInjectionContext(injector, () => (guard as CanLoadFn)(route, segments)), + ); return abortSignal ? obs$.pipe(takeUntilAbort(abortSignal)) : obs$; }); return of(canLoadObservables).pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer)); } +/** + * Calls a guard right away, but delivers a synchronous throw as an observable error so that + * `prioritizedGuardValue` orders it with the other guards' results. + */ +function callGuard(guardFn: () => T | Promise | Observable): Observable { + try { + return wrapIntoObservable(guardFn()); + } catch (e) { + return new Observable((subscriber) => subscriber.error(e)); + } +} + function redirectIfUrlTree(urlSerializer: UrlSerializer): OperatorFunction { return pipe( tap((result: GuardResult) => { @@ -276,12 +290,13 @@ export function runCanMatchGuards( const canMatchObservables = canMatch.map((injectionToken) => { const guard = getTokenOrFunctionIdentity(injectionToken as ProviderToken, injector); - const guardVal = isCanMatch(guard) - ? guard.canMatch(route, segments, currentSnapshot) - : runInInjectionContext(injector, () => - (guard as CanMatchFn)(route, segments, currentSnapshot), - ); - return wrapIntoObservable(guardVal).pipe(takeUntilAbort(abortSignal)); + return callGuard(() => + isCanMatch(guard) + ? guard.canMatch(route, segments, currentSnapshot) + : runInInjectionContext(injector, () => + (guard as CanMatchFn)(route, segments, currentSnapshot), + ), + ).pipe(takeUntilAbort(abortSignal)); }); return of(canMatchObservables).pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer)); diff --git a/packages/router/src/operators/prioritized_guard_value.ts b/packages/router/src/operators/prioritized_guard_value.ts index 01977b5f36a..6c2623f9dc9 100644 --- a/packages/router/src/operators/prioritized_guard_value.ts +++ b/packages/router/src/operators/prioritized_guard_value.ts @@ -6,8 +6,8 @@ * found in the LICENSE file at https://angular.dev/license */ -import {combineLatest, Observable, OperatorFunction} from 'rxjs'; -import {filter, map, startWith, switchMap, take} from 'rxjs/operators'; +import {combineLatest, Observable, of, OperatorFunction} from 'rxjs'; +import {catchError, filter, map, startWith, switchMap, take} from 'rxjs/operators'; import {GuardResult, RedirectCommand} from '../models'; import {isUrlTree, UrlTree} from '../url_tree'; @@ -18,7 +18,19 @@ declare type INTERIM_VALUES = typeof INITIAL_VALUE | GuardResult; export function prioritizedGuardValue(): OperatorFunction[], GuardResult> { return switchMap((obs) => { return combineLatest( - obs.map((o) => o.pipe(take(1), startWith(INITIAL_VALUE as INTERIM_VALUES))), + obs.map((o) => + o.pipe( + take(1), + // A thrown `RedirectCommand` is a result, so it must respect the guard order too. + catchError((e) => { + if (e instanceof RedirectCommand) { + return of(e); + } + throw e; + }), + startWith(INITIAL_VALUE as INTERIM_VALUES), + ), + ), ).pipe( map((results: INTERIM_VALUES[]) => { for (const result of results) { diff --git a/packages/router/test/integration/guards.spec.ts b/packages/router/test/integration/guards.spec.ts index 974bc7e17d8..7d874e0a7de 100644 --- a/packages/router/test/integration/guards.spec.ts +++ b/packages/router/test/integration/guards.spec.ts @@ -2610,6 +2610,133 @@ export function guardsIntegrationSuite() { expect(location.path()).toEqual('/b'); }); + it('should give priority to an earlier guard over a later guard that throws', async () => { + const router = TestBed.inject(Router); + const location = TestBed.inject(Location); + const fixture = await createRoot(router, RootCmp); + + let resolveFirstGuard!: (result: RedirectCommand) => void; + router.resetConfig([ + { + path: 'a', + canActivate: [ + () => new Promise((resolve) => (resolveFirstGuard = resolve)), + () => { + throw new RedirectCommand(router.parseUrl('/upgrade')); + }, + ], + component: BlankCmp, + }, + {path: 'login', component: BlankCmp}, + {path: 'upgrade', component: BlankCmp}, + ]); + + router.navigateByUrl('/a'); + await advance(fixture); + resolveFirstGuard(new RedirectCommand(router.parseUrl('/login'))); + await advance(fixture); + + expect(location.path()).toEqual('/login'); + }); + + it('should give priority to an earlier canDeactivate guard over a later guard that throws', async () => { + const router = TestBed.inject(Router); + const location = TestBed.inject(Location); + const fixture = await createRoot(router, RootCmp); + + let resolveFirstGuard!: (result: RedirectCommand) => void; + let firstGuardCalls = 0; + router.resetConfig([ + { + path: 'a', + // Leaving `/a` again for the redirect re-runs these guards, so only the first run blocks or throws. + canDeactivate: [ + () => + firstGuardCalls++ === 0 + ? new Promise((resolve) => (resolveFirstGuard = resolve)) + : true, + (_c: unknown, _route: unknown, _state: unknown, next: RouterStateSnapshot) => { + if (next.url === '/b') { + throw new RedirectCommand(router.parseUrl('/upgrade')); + } + return true; + }, + ], + component: BlankCmp, + }, + {path: 'b', component: BlankCmp}, + {path: 'login', component: BlankCmp}, + {path: 'upgrade', component: BlankCmp}, + ]); + + router.navigateByUrl('/a'); + await advance(fixture); + router.navigateByUrl('/b'); + await advance(fixture); + resolveFirstGuard(new RedirectCommand(router.parseUrl('/login'))); + await advance(fixture); + + expect(location.path()).toEqual('/login'); + }); + + it('should give priority to an earlier canMatch guard over a later guard that throws', async () => { + const router = TestBed.inject(Router); + const location = TestBed.inject(Location); + const fixture = await createRoot(router, RootCmp); + + let resolveFirstGuard!: (result: RedirectCommand) => void; + router.resetConfig([ + { + path: 'a', + canMatch: [ + () => new Promise((resolve) => (resolveFirstGuard = resolve)), + () => { + throw new RedirectCommand(router.parseUrl('/upgrade')); + }, + ], + component: BlankCmp, + }, + {path: 'login', component: BlankCmp}, + {path: 'upgrade', component: BlankCmp}, + ]); + + router.navigateByUrl('/a'); + await advance(fixture); + resolveFirstGuard(new RedirectCommand(router.parseUrl('/login'))); + await advance(fixture); + + expect(location.path()).toEqual('/login'); + }); + + it('should give priority to an earlier canLoad guard over a later guard that throws', async () => { + const router = TestBed.inject(Router); + const location = TestBed.inject(Location); + const fixture = await createRoot(router, RootCmp); + + let resolveFirstGuard!: (result: RedirectCommand) => void; + router.resetConfig([ + { + path: 'a', + canLoad: [ + () => new Promise((resolve) => (resolveFirstGuard = resolve)), + () => { + throw new RedirectCommand(router.parseUrl('/upgrade')); + }, + ], + loadChildren: () => [{path: '', component: BlankCmp}], + }, + {path: 'login', component: BlankCmp}, + {path: 'upgrade', component: BlankCmp}, + ]); + + router.navigateByUrl('/a'); + await advance(fixture); + resolveFirstGuard(new RedirectCommand(router.parseUrl('/login'))); + await advance(fixture); + + expect(location.path()).toEqual('/login'); + }); + it('should redirect when a resolver throws a RedirectCommand', async () => { const router = TestBed.inject(Router); const location = TestBed.inject(Location);