Sub topic 13
Observing Navigation with Router Events
This chapter assumes you know basic RxJS operators such as filter and pipe, the inject() function, and the route guards and resolvers from earlier chapters.
Each navigation passes through a fixed series of stages. The router matches the URL, runs guards, runs resolvers, and then activates components. At each stage, the Router service emits an event on its events Observable. If you subscribe to that stream, you can show loading indicators, record page views, or log failed navigations without changing any routed component.
The Navigation Lifecycle
The events you will use most often are listed below.
| Event | When it fires |
|---|---|
| `NavigationStart` | A navigation begins |
| `RoutesRecognized` | The URL has been matched to routes |
| `GuardsCheckEnd` | Guards have finished; `shouldActivate` holds the result |
| `ResolveEnd` | Resolvers have finished |
| `NavigationEnd` | The navigation completed successfully |
| `NavigationCancel` | A guard blocked the navigation, or a newer navigation replaced it |
| `NavigationError` | The navigation failed with an error |
| `NavigationSkipped` | The router ignored the navigation, for example a navigation to the URL that is already active |
Each navigation ends with exactly one of NavigationEnd, NavigationCancel, NavigationError, or NavigationSkipped.
A Global Loading Indicator
Resolvers delay activation, so users may need to see that something is happening. This root component turns a signal on when a navigation starts and off when it finishes in any way:
import { Component, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
Event,
NavigationCancel,
NavigationEnd,
NavigationError,
NavigationSkipped,
NavigationStart,
Router,
RouterOutlet
} from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
template: `
@if (loading()) {
<div class="progress">Loading…</div>
}
<router-outlet />
`
})
export class AppComponent {
readonly loading = signal(false);
private router = inject(Router);
constructor() {
this.router.events.pipe(takeUntilDestroyed()).subscribe((event: Event) => {
if (event instanceof NavigationStart) {
this.loading.set(true);
} else if (
event instanceof NavigationEnd ||
event instanceof NavigationCancel ||
event instanceof NavigationError ||
event instanceof NavigationSkipped
) {
this.loading.set(false);
}
});
}
}Tracking Page Views
To react only to completed navigations, narrow the stream with filter and a type guard:
import { inject, Injectable } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class PageViewTracker {
private router = inject(Router);
start(): void {
this.router.events
.pipe(filter((e): e is NavigationEnd => e instanceof NavigationEnd))
.subscribe(e => console.log('Page view:', e.urlAfterRedirects));
}
}Use urlAfterRedirects instead of url. If a user visits /, url is /, but urlAfterRedirects is /home, which is the page they actually see. This service lives for the whole application, so leaving its subscription open is fine.
Debugging with Tracing
When a navigation behaves unexpectedly, turn on tracing to log every router event to the console:
import { provideRouter, withDebugTracing } from '@angular/router';
// In bootstrapApplication providers:
provideRouter(routes, withDebugTracing());Remove this before shipping because it produces a lot of console output.
Exercise
A guard on /dashboard returns router.createUrlTree(['/login']) for signed-out users. Which terminal event does the original navigation to /dashboard emit, and what happens next?
Show answer
The /dashboard navigation ends with NavigationCancel, because the guard's UrlTree redirect cancels it. The router then starts a new navigation to /login, which emits its own NavigationStart and ends with NavigationEnd if it succeeds.
Exercise
Why does the loading indicator example use takeUntilDestroyed() while PageViewTracker does not?
Show answer
The component subscribes inside its constructor, and takeUntilDestroyed() closes that subscription when the component is destroyed so it doesn't leak. PageViewTracker is a root singleton that lasts as long as the application, so its subscription never needs to be closed.