Sub topic 13
Observing Navigation with Router Events
Every navigation in Angular runs through a fixed pipeline: match the URL, run guards, run resolvers, activate components. The Router reports each stage as an event on the Router.events observable. When you subscribe to that stream you can show a loading bar, record page views, log failed navigations, or debug a route that never seems to activate.
This chapter assumes you know RxJS operators such as filter and map, standalone components, the inject() function, and the guards and resolvers covered in the previous chapters.
The Navigation Lifecycle
A navigation starts when the user clicks a RouterLink, when code calls Router.navigate, or when the browser's back button changes the URL. From then on, the Router emits events in a predictable order. Guards and resolvers each have start and end events, so you can see exactly where a navigation spends its time or where it stops.
Lazy loading adds RouteConfigLoadStart and RouteConfigLoadEnd around the download of a loadChildren or loadComponent chunk. Child routes also emit ChildActivationStart and ChildActivationEnd.
The Event Types
| Event | When it fires | Useful properties |
|---|---|---|
| `NavigationStart` | A navigation begins | `url`, `navigationTrigger` (`imperative`, `popstate`, `hashchange`) |
| `RoutesRecognized` | The URL has been matched to routes | `urlAfterRedirects`, `state` |
| `GuardsCheckStart` / `GuardsCheckEnd` | Guards begin or finish running | `shouldActivate` on the end event |
| `ResolveStart` / `ResolveEnd` | Resolvers begin or finish | `state` |
| `RouteConfigLoadStart` / `RouteConfigLoadEnd` | A lazy route's code is being fetched | `route` |
| `ActivationStart` / `ActivationEnd` | A route is about to be activated or has been | `snapshot` |
| `NavigationEnd` | Navigation succeeded | `url`, `urlAfterRedirects` |
| `NavigationCancel` | A guard rejected, a redirect replaced it, or a newer navigation superseded it | `reason`, `code` |
| `NavigationError` | Something threw, for example a resolver | `error` |
| `NavigationSkipped` | The Router ignored the navigation, for example a same-URL click | `reason` |
| `Scroll` | Scroll position info after navigation | `position`, `anchor` |
A navigation finishes with exactly one of NavigationEnd, NavigationCancel, NavigationError, or NavigationSkipped. Most bugs in event-driven code come from forgetting the last three.
Subscribing to Router.events
Router.events emits every event type, so you almost always narrow it with filter. A type-guard predicate makes TypeScript treat the filtered values as the specific class, which gives you autocomplete on properties like urlAfterRedirects.
import { Injectable, inject } from '@angular/core';
import { Router, NavigationEnd } 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 => {
// urlAfterRedirects is the URL the user actually ends up on
console.log('page view', e.urlAfterRedirects);
});
}
}The service is a root singleton that lives as long as the application, so it never needs to unsubscribe. The service has to start before the first navigation, though. Otherwise it misses the initial page view. In Angular 19 and later, provideAppInitializer runs it during bootstrap:
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { inject, provideAppInitializer } from '@angular/core';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app.component';
import { routes } from './app.routes';
import { PageViewTracker } from './page-view-tracker.service';
bootstrapApplication(AppComponent, {
providers: [
provideRouter(routes),
provideAppInitializer(() => inject(PageViewTracker).start())
]
});Building a Navigation Loading Indicator
A global loading bar is the classic use of router events. It turns on at NavigationStart and turns off when the navigation ends, whichever way it ends. A signal holds the state, and takeUntilDestroyed cleans up the subscription when the component is destroyed.
import { Component, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
Router,
RouterOutlet,
NavigationStart,
NavigationEnd,
NavigationCancel,
NavigationError,
NavigationSkipped
} from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
template: `
@if (loading()) {
<div class="loading-bar" role="progressbar" aria-label="Loading page"></div>
}
<router-outlet />
`
})
export class AppComponent {
readonly loading = signal(false);
private router = inject(Router);
constructor() {
this.router.events.pipe(takeUntilDestroyed()).subscribe(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);
}
});
}
}takeUntilDestroyed() with no argument has to be called in an injection context. A constructor or a field initializer works. Inside ngOnInit you must pass it a DestroyRef.
If guards and resolvers are fast and you only want feedback while lazy chunks download, listen to RouteConfigLoadStart and RouteConfigLoadEnd instead. Several lazy configs can load in one navigation, so keep a counter rather than a boolean.
Diagnosing Cancelled and Failed Navigations
NavigationCancel carries a code from the NavigationCancellationCode enum. It tells you why the navigation stopped:
GuardRejected: a guard returnedfalse.Redirect: a guard or resolver returned aUrlTree, so a new navigation replaced this one. This is normal behaviour for an auth guard and should not be logged as a problem.SupersededByNewNavigation: the user clicked another link before this navigation finished.NoDataFromResolver: a resolver's observable completed without emitting a value.
import { inject } from '@angular/core';
import { Router, NavigationCancel, NavigationCancellationCode, NavigationError } from '@angular/router';
import { filter } from 'rxjs';
export function logNavigationProblems(): void {
const router = inject(Router);
router.events
.pipe(filter(e => e instanceof NavigationCancel || e instanceof NavigationError))
.subscribe(e => {
if (e instanceof NavigationError) {
console.error('Navigation failed:', e.url, e.error);
} else if (e instanceof NavigationCancel && e.code === NavigationCancellationCode.GuardRejected) {
console.warn('Blocked by guard:', e.url);
}
});
}Call logNavigationProblems from provideAppInitializer, just like the tracker. To recover from errors rather than just log them, provideRouter(routes, withNavigationErrorHandler(handler)) lets you run code for every NavigationError in an injection context. A common pattern is to redirect to an error page from there.
Common Mistakes
- The spinner never stops. You turned it off only on
NavigationEnd. Guards that redirect, resolver errors, and same-URL clicks never emit that event. - Analytics records the wrong URL.
NavigationEnd.urlis the URL that was requested. After aredirectTo,urlAfterRedirectsis the page the user actually sees. - The first page view is missing. The subscriber was created after bootstrap navigation had already started. Start it with
provideAppInitializeror in the root component's constructor. - Router events do work that belongs in a guard or resolver. For example, a
NavigationStarthandler that checks login and callsnavigate. That approach fights the Router's pipeline and causes double navigations. Events are for observing. Guards and resolvers are for deciding. - Memory leaks. Components that subscribe and are destroyed need
takeUntilDestroyedor an explicit unsubscribe, becauseRouter.eventsnever completes.
Exercise
An auth guard on /dashboard returns router.createUrlTree(['/login']) for signed-out users. A signed-out user clicks a link to /dashboard. List the terminal events (NavigationEnd, NavigationCancel, NavigationError) emitted and the URL each refers to, and say which NavigationCancellationCode appears.
Show answer
Two navigations run. The first, to /dashboard, ends with NavigationCancel, whose code is NavigationCancellationCode.Redirect, because the guard returned a UrlTree. The Router then starts a new navigation to /login, which ends with NavigationEnd with url and urlAfterRedirects equal to /login. No NavigationError is emitted.
Exercise
A lazy-loaded ReportsComponent subscribes to router.events in its constructor, filtered to NavigationEnd, to set a page heading from the URL. The heading stays empty when the user first opens /reports but updates on later navigations. Why, and how do you fix it?
Show answer
The component is created during the activation stage of the /reports navigation, and NavigationEnd for that navigation is emitted either before the subscription exists or in a way the component cannot rely on. Router.events does not replay events. Fix it by reading the current state once at creation (router.url, or better the ActivatedRoute or a component input) and using the event stream only for later changes. Alternatively, move the logic into a root-level service started with provideAppInitializer.
Exercise
Write the filter predicate that narrows Router.events to only RouteConfigLoadStart and RouteConfigLoadEnd, and explain why a loading counter is safer than a boolean for these events.
Show answer
filter((e): e is RouteConfigLoadStart | RouteConfigLoadEnd => e instanceof RouteConfigLoadStart || e instanceof RouteConfigLoadEnd). One navigation can trigger several lazy loads, for example a lazy parent and a lazy child component. With a boolean, the first RouteConfigLoadEnd hides the indicator while another chunk is still downloading. A counter goes up on each start and down on each end, and the indicator shows while the count is above zero.