Sub topic 14
Showing progress during slow navigations
This chapter assumes you can write a functional guard and a ResolveFn, and that you know basic RxJS operators and Angular signals. You will add a loading indicator that tracks every navigation. It will not flicker on fast navigations, and it will always turn off, whatever way the navigation ends.
Why the screen looks frozen
While guards and resolvers run, the router keeps the current page on screen. A resolver that calls a slow API makes a click look like it did nothing. Users click again, and the router cancels the first navigation and starts a second one.
The router does not draw a spinner for you. It publishes events on Router.events, and you turn those events into UI state.
The events that matter
A successful navigation emits these events in order. Many others exist, such as ChildActivationStart, and you can ignore them here.
| Event | Meaning |
|---|---|
| `NavigationStart` | The router accepted the request and began working. |
| `RoutesRecognized` | The URL was matched to a route tree. |
| `GuardsCheckStart` / `GuardsCheckEnd` | Guards ran. |
| `ResolveStart` / `ResolveEnd` | Resolvers ran. |
| `NavigationEnd` | The new route is active. |
Every navigation ends with exactly one of four events:
NavigationEnd: it succeeded.NavigationCancel: a guard returnedfalseor aUrlTree, or a newer navigation replaced it.NavigationError: something threw, such as a resolver that errored without a catch.NavigationSkipped: the router ignored the request, for example because the URL equals the current one andonSameUrlNavigationis'ignore'.
Handle all four. The most common bug is to listen only for NavigationEnd. The spinner then stays on forever after a guard redirects or a resolver fails.
A first version: a global busy flag
This service turns the event stream into a busy signal. It is true from NavigationStart until any of the four end events.
import { Injectable, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import {
NavigationCancel,
NavigationEnd,
NavigationError,
NavigationSkipped,
NavigationStart,
Router,
} from '@angular/router';
import { filter, map } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class NavigationProgress {
private readonly router = inject(Router);
readonly busy = toSignal(
this.router.events.pipe(
map((event) => {
if (event instanceof NavigationStart) {
return true;
}
if (
event instanceof NavigationEnd ||
event instanceof NavigationCancel ||
event instanceof NavigationError ||
event instanceof NavigationSkipped
) {
return false;
}
return null;
}),
filter((value): value is boolean => value !== null),
),
{ initialValue: false },
);
}toSignal subscribes in the injection context where the service is created and unsubscribes when that context is destroyed. Because the service is providedIn: 'root', it lives as long as the app.
Use the signal in the root component, which always exists:
import { Component, inject } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { NavigationProgress } from './navigation-progress';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
template: `
@if (progress.busy()) {
<div class="top-bar" role="progressbar" aria-label="Loading page"></div>
}
<router-outlet />
`,
})
export class AppComponent {
protected readonly progress = inject(NavigationProgress);
}Fixing the flicker
The first version has a visible flaw. A navigation that takes 40 ms flashes the bar for one frame. A guard redirect also emits NavigationCancel and then NavigationStart almost at once, so the bar blinks off and on.
The standard fix is to delay the "on" state. Show the indicator only if the navigation is still running after a short threshold, such as 150 ms. Use switchMap so that an end event cancels the pending timer:
import { Injectable, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import {
NavigationCancel,
NavigationEnd,
NavigationError,
NavigationSkipped,
NavigationStart,
Router,
} from '@angular/router';
import { distinctUntilChanged, filter, map, of, switchMap, timer } from 'rxjs';
const SHOW_AFTER_MS = 150;
@Injectable({ providedIn: 'root' })
export class NavigationProgress {
private readonly router = inject(Router);
readonly busy = toSignal(
this.router.events.pipe(
map((event) => {
if (event instanceof NavigationStart) {
return true;
}
if (
event instanceof NavigationEnd ||
event instanceof NavigationCancel ||
event instanceof NavigationError ||
event instanceof NavigationSkipped
) {
return false;
}
return null;
}),
filter((value): value is boolean => value !== null),
switchMap((isBusy) =>
isBusy ? timer(SHOW_AFTER_MS).pipe(map(() => true)) : of(false),
),
distinctUntilChanged(),
),
{ initialValue: false },
);
}Here is how it behaves:
NavigationStartstarts a 150 ms timer.- If
NavigationEndarrives first,switchMapdrops the timer and emitsfalse. The user never sees the bar. - If the timer fires first, the bar appears. It stays until an end event arrives.
- In a redirect, the
falsefromNavigationCancelis immediately replaced by a new timer.distinctUntilChangedsuppresses repeatedfalsevalues.
Some designs also enforce a minimum display time, such as 300 ms, so the bar does not flash briefly once it has appeared. Add that only if testers complain. It makes every slow navigation feel slightly slower.
Showing progress for one phase only
You do not have to track the whole navigation. If only resolvers are slow, switch on ResolveStart and off on ResolveEnd. Remember that a failed or cancelled navigation may never emit ResolveEnd, so still reset on the four end events.
RouteConfigLoadStart and RouteConfigLoadEnd bracket the download of lazy loadChildren configuration. They can drive a separate "loading module" message.
Alternatives to a global bar
| Approach | Good for | Cost |
|---|---|---|
| Global bar from router events | Any app. One place, no per-route work. | The old page stays visible and does not change. |
| Skip the resolver and show a skeleton in the component | Pages where partial content is useful. | The component handles loading and error states. |
| Resolver plus a global bar | Pages that make no sense without their data. | The user waits on the previous page. |
A resolver is a good choice when the page cannot render without its data. When the page can show a header first and fill in the rest later, a skeleton in the component usually feels faster.
Accessibility
A moving bar is invisible to screen reader users. The role="progressbar" and aria-label in the example give them a name for the state. You can also set aria-busy on the main content container while busy() is true. Respect prefers-reduced-motion in the bar's CSS animation.
Checklist
- Start on
NavigationStart. - Stop on
NavigationEnd,NavigationCancel,NavigationErrorandNavigationSkipped. - Delay the display by about 150 ms to avoid flicker.
- Keep the logic in one service so every route gets it for free.
Exercise
A developer sets a loading flag to true on NavigationStart and false on NavigationEnd. After a user hits a page protected by an authGuard that redirects to /login, the spinner never goes away. Why does it happen, and what is the fix?
Show answer
A guard that returns a UrlTree cancels the original navigation, so the router emits NavigationCancel for it and starts a new navigation to /login. The flag was set by the first NavigationStart. Because NavigationEnd fired only for the second navigation, the order of events can leave the flag wrong, and failed navigations (NavigationError) or ignored ones (NavigationSkipped) never reach NavigationEnd at all. The fix is to reset the flag on all four end events: NavigationEnd, NavigationCancel, NavigationError and NavigationSkipped. Adding a short switchMap(timer) delay also hides the brief off-and-on blink during the redirect.
Exercise
Why does the debounced version use switchMap and not mergeMap or concatMap?
Show answer
switchMap unsubscribes from the previous inner observable when a new event arrives. When NavigationEnd arrives, the pending 150 ms timer from NavigationStart is dropped, so the bar never turns on for a fast navigation. mergeMap would let the old timer still fire and set the flag to true after the navigation had already finished. concatMap would queue the events instead of cancelling, delaying the "off" signal.