mirror of
https://github.com/angular/angular.git
synced 2026-11-23 07:05:14 -05:00
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 21dd0171b3)
This commit is contained in:
committed by
leonsenft
parent
702ba3a2eb
commit
2f0e2ac5e7
@@ -444,6 +444,7 @@
|
||||
"bootstrapApplication",
|
||||
"borrowReactiveLViewConsumer",
|
||||
"cacheMatchingLocalNames",
|
||||
"callGuard",
|
||||
"callHook",
|
||||
"callHookInternal",
|
||||
"callHooks",
|
||||
|
||||
@@ -217,12 +217,13 @@ function runCanDeactivate(
|
||||
const canDeactivateObservables = canDeactivate.map((c: any) => {
|
||||
const closestInjector = currARS._environmentInjector;
|
||||
const guard = getTokenOrFunctionIdentity<any>(c, closestInjector);
|
||||
const guardVal = isCanDeactivate(guard)
|
||||
? guard.canDeactivate(component, currARS, currRSS, futureRSS)
|
||||
: runInInjectionContext(closestInjector, () =>
|
||||
(guard as CanDeactivateFn<any>)(component, currARS, currRSS, futureRSS),
|
||||
);
|
||||
return wrapIntoObservable(guardVal).pipe(first());
|
||||
return callGuard(() =>
|
||||
isCanDeactivate(guard)
|
||||
? guard.canDeactivate(component, currARS, currRSS, futureRSS)
|
||||
: runInInjectionContext(closestInjector, () =>
|
||||
(guard as CanDeactivateFn<any>)(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<any>(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<T>(guardFn: () => T | Promise<T> | Observable<T>): Observable<T> {
|
||||
try {
|
||||
return wrapIntoObservable(guardFn());
|
||||
} catch (e) {
|
||||
return new Observable<T>((subscriber) => subscriber.error(e));
|
||||
}
|
||||
}
|
||||
|
||||
function redirectIfUrlTree(urlSerializer: UrlSerializer): OperatorFunction<GuardResult, boolean> {
|
||||
return pipe(
|
||||
tap((result: GuardResult) => {
|
||||
@@ -276,12 +290,13 @@ export function runCanMatchGuards(
|
||||
|
||||
const canMatchObservables = canMatch.map((injectionToken) => {
|
||||
const guard = getTokenOrFunctionIdentity(injectionToken as ProviderToken<any>, 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));
|
||||
|
||||
@@ -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<Observable<GuardResult>[], 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) {
|
||||
|
||||
@@ -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<RedirectCommand>((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<RedirectCommand>((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<RedirectCommand>((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<RedirectCommand>((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);
|
||||
|
||||
Reference in New Issue
Block a user