Skip to content

Commit 2f0e2ac

Browse files
MeAkibleonsenft
authored andcommitted
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 21dd017)
1 parent 702ba3a commit 2f0e2ac

4 files changed

Lines changed: 174 additions & 19 deletions

File tree

‎packages/core/test/bundling/router/bundle.golden_symbols.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,7 @@
444444
"bootstrapApplication",
445445
"borrowReactiveLViewConsumer",
446446
"cacheMatchingLocalNames",
447+
"callGuard",
447448
"callHook",
448449
"callHookInternal",
449450
"callHooks",

‎packages/router/src/operators/check_guards.ts‎

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -217,12 +217,13 @@ function runCanDeactivate(
217217
const canDeactivateObservables = canDeactivate.map((c: any) => {
218218
const closestInjector = currARS._environmentInjector;
219219
const guard = getTokenOrFunctionIdentity<any>(c, closestInjector);
220-
const guardVal = isCanDeactivate(guard)
221-
? guard.canDeactivate(component, currARS, currRSS, futureRSS)
222-
: runInInjectionContext(closestInjector, () =>
223-
(guard as CanDeactivateFn<any>)(component, currARS, currRSS, futureRSS),
224-
);
225-
return wrapIntoObservable(guardVal).pipe(first());
220+
return callGuard(() =>
221+
isCanDeactivate(guard)
222+
? guard.canDeactivate(component, currARS, currRSS, futureRSS)
223+
: runInInjectionContext(closestInjector, () =>
224+
(guard as CanDeactivateFn<any>)(component, currARS, currRSS, futureRSS),
225+
),
226+
).pipe(first());
226227
});
227228
return of(canDeactivateObservables).pipe(prioritizedGuardValue());
228229
}
@@ -242,16 +243,29 @@ export function runCanLoadGuards(
242243

243244
const canLoadObservables = canLoad.map((injectionToken: any) => {
244245
const guard = getTokenOrFunctionIdentity<any>(injectionToken, injector);
245-
const guardVal = isCanLoad(guard)
246-
? guard.canLoad(route, segments)
247-
: runInInjectionContext(injector, () => (guard as CanLoadFn)(route, segments));
248-
const obs$ = wrapIntoObservable(guardVal);
246+
const obs$ = callGuard(() =>
247+
isCanLoad(guard)
248+
? guard.canLoad(route, segments)
249+
: runInInjectionContext(injector, () => (guard as CanLoadFn)(route, segments)),
250+
);
249251
return abortSignal ? obs$.pipe(takeUntilAbort(abortSignal)) : obs$;
250252
});
251253

252254
return of(canLoadObservables).pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer));
253255
}
254256

257+
/**
258+
* Calls a guard right away, but delivers a synchronous throw as an observable error so that
259+
* `prioritizedGuardValue` orders it with the other guards' results.
260+
*/
261+
function callGuard<T>(guardFn: () => T | Promise<T> | Observable<T>): Observable<T> {
262+
try {
263+
return wrapIntoObservable(guardFn());
264+
} catch (e) {
265+
return new Observable<T>((subscriber) => subscriber.error(e));
266+
}
267+
}
268+
255269
function redirectIfUrlTree(urlSerializer: UrlSerializer): OperatorFunction<GuardResult, boolean> {
256270
return pipe(
257271
tap((result: GuardResult) => {
@@ -276,12 +290,13 @@ export function runCanMatchGuards(
276290

277291
const canMatchObservables = canMatch.map((injectionToken) => {
278292
const guard = getTokenOrFunctionIdentity(injectionToken as ProviderToken<any>, injector);
279-
const guardVal = isCanMatch(guard)
280-
? guard.canMatch(route, segments, currentSnapshot)
281-
: runInInjectionContext(injector, () =>
282-
(guard as CanMatchFn)(route, segments, currentSnapshot),
283-
);
284-
return wrapIntoObservable(guardVal).pipe(takeUntilAbort(abortSignal));
293+
return callGuard(() =>
294+
isCanMatch(guard)
295+
? guard.canMatch(route, segments, currentSnapshot)
296+
: runInInjectionContext(injector, () =>
297+
(guard as CanMatchFn)(route, segments, currentSnapshot),
298+
),
299+
).pipe(takeUntilAbort(abortSignal));
285300
});
286301

287302
return of(canMatchObservables).pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer));

‎packages/router/src/operators/prioritized_guard_value.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9-
import {combineLatest, Observable, OperatorFunction} from 'rxjs';
10-
import {filter, map, startWith, switchMap, take} from 'rxjs/operators';
9+
import {combineLatest, Observable, of, OperatorFunction} from 'rxjs';
10+
import {catchError, filter, map, startWith, switchMap, take} from 'rxjs/operators';
1111

1212
import {GuardResult, RedirectCommand} from '../models';
1313
import {isUrlTree, UrlTree} from '../url_tree';
@@ -18,7 +18,19 @@ declare type INTERIM_VALUES = typeof INITIAL_VALUE | GuardResult;
1818
export function prioritizedGuardValue(): OperatorFunction<Observable<GuardResult>[], GuardResult> {
1919
return switchMap((obs) => {
2020
return combineLatest(
21-
obs.map((o) => o.pipe(take(1), startWith(INITIAL_VALUE as INTERIM_VALUES))),
21+
obs.map((o) =>
22+
o.pipe(
23+
take(1),
24+
// A thrown `RedirectCommand` is a result, so it must respect the guard order too.
25+
catchError((e) => {
26+
if (e instanceof RedirectCommand) {
27+
return of(e);
28+
}
29+
throw e;
30+
}),
31+
startWith(INITIAL_VALUE as INTERIM_VALUES),
32+
),
33+
),
2234
).pipe(
2335
map((results: INTERIM_VALUES[]) => {
2436
for (const result of results) {

‎packages/router/test/integration/guards.spec.ts‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2610,6 +2610,133 @@ export function guardsIntegrationSuite() {
26102610
expect(location.path()).toEqual('/b');
26112611
});
26122612

2613+
it('should give priority to an earlier guard over a later guard that throws', async () => {
2614+
const router = TestBed.inject(Router);
2615+
const location = TestBed.inject(Location);
2616+
const fixture = await createRoot(router, RootCmp);
2617+
2618+
let resolveFirstGuard!: (result: RedirectCommand) => void;
2619+
router.resetConfig([
2620+
{
2621+
path: 'a',
2622+
canActivate: [
2623+
() => new Promise<RedirectCommand>((resolve) => (resolveFirstGuard = resolve)),
2624+
() => {
2625+
throw new RedirectCommand(router.parseUrl('/upgrade'));
2626+
},
2627+
],
2628+
component: BlankCmp,
2629+
},
2630+
{path: 'login', component: BlankCmp},
2631+
{path: 'upgrade', component: BlankCmp},
2632+
]);
2633+
2634+
router.navigateByUrl('/a');
2635+
await advance(fixture);
2636+
resolveFirstGuard(new RedirectCommand(router.parseUrl('/login')));
2637+
await advance(fixture);
2638+
2639+
expect(location.path()).toEqual('/login');
2640+
});
2641+
2642+
it('should give priority to an earlier canDeactivate guard over a later guard that throws', async () => {
2643+
const router = TestBed.inject(Router);
2644+
const location = TestBed.inject(Location);
2645+
const fixture = await createRoot(router, RootCmp);
2646+
2647+
let resolveFirstGuard!: (result: RedirectCommand) => void;
2648+
let firstGuardCalls = 0;
2649+
router.resetConfig([
2650+
{
2651+
path: 'a',
2652+
// Leaving `/a` again for the redirect re-runs these guards, so only the first run blocks or throws.
2653+
canDeactivate: [
2654+
() =>
2655+
firstGuardCalls++ === 0
2656+
? new Promise<RedirectCommand>((resolve) => (resolveFirstGuard = resolve))
2657+
: true,
2658+
(_c: unknown, _route: unknown, _state: unknown, next: RouterStateSnapshot) => {
2659+
if (next.url === '/b') {
2660+
throw new RedirectCommand(router.parseUrl('/upgrade'));
2661+
}
2662+
return true;
2663+
},
2664+
],
2665+
component: BlankCmp,
2666+
},
2667+
{path: 'b', component: BlankCmp},
2668+
{path: 'login', component: BlankCmp},
2669+
{path: 'upgrade', component: BlankCmp},
2670+
]);
2671+
2672+
router.navigateByUrl('/a');
2673+
await advance(fixture);
2674+
router.navigateByUrl('/b');
2675+
await advance(fixture);
2676+
resolveFirstGuard(new RedirectCommand(router.parseUrl('/login')));
2677+
await advance(fixture);
2678+
2679+
expect(location.path()).toEqual('/login');
2680+
});
2681+
2682+
it('should give priority to an earlier canMatch guard over a later guard that throws', async () => {
2683+
const router = TestBed.inject(Router);
2684+
const location = TestBed.inject(Location);
2685+
const fixture = await createRoot(router, RootCmp);
2686+
2687+
let resolveFirstGuard!: (result: RedirectCommand) => void;
2688+
router.resetConfig([
2689+
{
2690+
path: 'a',
2691+
canMatch: [
2692+
() => new Promise<RedirectCommand>((resolve) => (resolveFirstGuard = resolve)),
2693+
() => {
2694+
throw new RedirectCommand(router.parseUrl('/upgrade'));
2695+
},
2696+
],
2697+
component: BlankCmp,
2698+
},
2699+
{path: 'login', component: BlankCmp},
2700+
{path: 'upgrade', component: BlankCmp},
2701+
]);
2702+
2703+
router.navigateByUrl('/a');
2704+
await advance(fixture);
2705+
resolveFirstGuard(new RedirectCommand(router.parseUrl('/login')));
2706+
await advance(fixture);
2707+
2708+
expect(location.path()).toEqual('/login');
2709+
});
2710+
2711+
it('should give priority to an earlier canLoad guard over a later guard that throws', async () => {
2712+
const router = TestBed.inject(Router);
2713+
const location = TestBed.inject(Location);
2714+
const fixture = await createRoot(router, RootCmp);
2715+
2716+
let resolveFirstGuard!: (result: RedirectCommand) => void;
2717+
router.resetConfig([
2718+
{
2719+
path: 'a',
2720+
canLoad: [
2721+
() => new Promise<RedirectCommand>((resolve) => (resolveFirstGuard = resolve)),
2722+
() => {
2723+
throw new RedirectCommand(router.parseUrl('/upgrade'));
2724+
},
2725+
],
2726+
loadChildren: () => [{path: '', component: BlankCmp}],
2727+
},
2728+
{path: 'login', component: BlankCmp},
2729+
{path: 'upgrade', component: BlankCmp},
2730+
]);
2731+
2732+
router.navigateByUrl('/a');
2733+
await advance(fixture);
2734+
resolveFirstGuard(new RedirectCommand(router.parseUrl('/login')));
2735+
await advance(fixture);
2736+
2737+
expect(location.path()).toEqual('/login');
2738+
});
2739+
26132740
it('should redirect when a resolver throws a RedirectCommand', async () => {
26142741
const router = TestBed.inject(Router);
26152742
const location = TestBed.inject(Location);

0 commit comments

Comments
 (0)