Skip to content

Commit 43cbf76

Browse files
committed
fix(router): don't reload the page when restoring the URL with the Navigation API
When a navigation is cancelled or fails after its URL was committed, the platform navigation integration puts the previous URL back with `navigation.navigate()` and leaves that navigate event alone. A navigation nobody intercepts loads a new document, so the whole app reloads instead of just getting its URL back. With the default `canceledNavigationResolution`, this happens when a routed component throws during activation, when a guard rejects with `urlUpdateStrategy: 'eager'`, and in browsers without `precommitHandler` support (Safari) when a guard rejects a navigation started outside the router, like a plain link or the back button. Intercept that navigation as well, without a handler, so only the URL changes. Fixes angular#71596
1 parent 78220d3 commit 43cbf76

2 files changed

Lines changed: 57 additions & 1 deletion

File tree

‎packages/router/src/statemanager/navigation_state_manager.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,10 @@ export class NavigationStateManager extends StateManager {
413413

414414
const routerInfo = (event?.info as NavigationInfo | undefined)?.ɵrouterInfo;
415415
if (routerInfo && !routerInfo.intercept) {
416+
// The router is restoring the URL after a cancelled or failed navigation. This must not
417+
// start a router navigation, but it still has to be intercepted: otherwise the browser
418+
// loads the URL as a new document and the whole app reloads.
419+
event.intercept({focusReset: 'manual', scroll: 'manual'});
416420
return;
417421
}
418422
const isTriggeredByRouterTransition = !!routerInfo;

‎packages/router/test/with_platform_navigation.spec.ts‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
provideRouter,
1313
Event,
1414
Router,
15+
RouterOutlet,
1516
UrlSerializer,
1617
DefaultUrlSerializer,
1718
UrlTree,
@@ -33,7 +34,7 @@ import {
3334
provideLocationMocks,
3435
MOCK_PLATFORM_LOCATION_CONFIG,
3536
} from '@angular/common/testing';
36-
import {inject} from '@angular/core';
37+
import {Component, DestroyRef, inject} from '@angular/core';
3738

3839
/// <reference types="dom-navigation" />
3940

@@ -510,6 +511,57 @@ if (typeof window !== 'undefined' && 'navigation' in window && !isFirefox()) {
510511
expect(routerEvents).toEqual([]);
511512
}),
512513
);
514+
515+
/**
516+
* Cancels the navigations that nothing intercepted and that would load a new document, so the
517+
* test page stays where it is. Returns the URLs of those navigations.
518+
*/
519+
function preventCrossDocumentNavigations(): string[] {
520+
const urls: string[] = [];
521+
const intercept = spyOn(NavigateEvent.prototype, 'intercept').and.callThrough();
522+
const controller = new AbortController();
523+
TestBed.inject(PlatformNavigation).addEventListener(
524+
'navigate',
525+
(e: NavigateEvent) => {
526+
const intercepted = intercept.calls.all().some((call) => call.object === e);
527+
if (!intercepted && !e.destination.sameDocument) {
528+
urls.push(e.destination.url);
529+
e.preventDefault();
530+
}
531+
},
532+
{signal: controller.signal},
533+
);
534+
TestBed.inject(DestroyRef).onDestroy(() => controller.abort());
535+
return urls;
536+
}
537+
538+
it('should restore the URL without reloading the page when activation fails', async () => {
539+
@Component({template: '<router-outlet />', imports: [RouterOutlet]})
540+
class RootCmp {}
541+
542+
@Component({template: ''})
543+
class ThrowingCmp {
544+
constructor() {
545+
throw new Error('error during activation');
546+
}
547+
}
548+
549+
router.resetConfig([
550+
{path: 'throwing', component: ThrowingCmp},
551+
{path: '**', children: []},
552+
]);
553+
const fixture = TestBed.createComponent(RootCmp);
554+
await fixture.whenStable();
555+
const urlBefore = window.location.href;
556+
const crossDocumentNavigations = preventCrossDocumentNavigations();
557+
558+
// The URL is committed right before activation, so the router has to restore it.
559+
await expectAsync(router.navigateByUrl('/throwing')).toBeRejected();
560+
await timeout();
561+
562+
expect(crossDocumentNavigations).toEqual([]);
563+
expect(window.location.href).toBe(urlBefore);
564+
});
513565
});
514566

515567
describe('focusReset with real platform navigation', () => {

0 commit comments

Comments
 (0)