Sub topic 1
How the router navigates: a short lifecycle tour
Guards and resolvers are hooks into the router's navigation process. Before you write either one, you need to know where in that process each hook runs. This chapter walks through one navigation from start to finish. Later chapters cover each hook in detail.
Prerequisites
This chapter assumes you have the following:
- Basic TypeScript, including types and arrow functions.
- Angular components, services and dependency injection.
- Angular routing basics: a
Routesarray,<router-outlet>,routerLinkand route parameters. - Some familiarity with RxJS Observables, because the router exposes its progress as an Observable.
What a navigation is
A navigation is the router's attempt to move from the current URL to a new one. Several things can start one:
- The user clicks a
routerLink. - Your code calls
router.navigate()orrouter.navigateByUrl(). - The user types a URL, or uses the browser's back or forward button.
- The app loads for the first time (the initial navigation).
Every navigation is a pipeline with a fixed order of steps. A step can succeed, cancel the navigation, redirect it, or fail. Nothing on screen changes until the pipeline reaches the activation step. If an earlier step stops the navigation, the user keeps seeing the current page.
The stages of one navigation
The router moves through these stages in order.
| Stage | What happens | Hooks that run here |
|---|---|---|
| 1. Start | The router accepts the request and begins a new navigation. | None |
| 2. Recognize | The router matches the URL against your `Routes`, applies redirects, and loads lazy routes. It builds the target router state. | `canMatch` |
| 3. Guards | The router checks whether leaving the old routes and entering the new ones is allowed. | `canDeactivate`, `canActivateChild`, `canActivate` |
| 4. Resolve | The router runs resolvers and waits for their data. | `resolve` |
| 5. Activate | The router creates components, binds data and updates the URL. | None |
| 6. End | The navigation is finished. | None |
The router can run canMatch guards during stage 2, before it has finished deciding which routes match. That is why canMatch can stop a lazy-loaded route from being downloaded. A later chapter covers it.
Guards run before resolvers. A guard that rejects the navigation therefore prevents the resolver's data request from being sent at all.
Watching it happen with router events
The router publishes each step as an event on Router.events. Logging these events is the quickest way to see the lifecycle in your own app. Every router event has a type property whose value comes from the EventType enum, so you can print readable names without comparing classes.
import { Component, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { EventType, Router, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
template: `<router-outlet />`,
})
export class AppComponent {
constructor() {
inject(Router)
.events.pipe(takeUntilDestroyed())
.subscribe((event) => console.log(EventType[event.type]));
}
}Navigating to a route that has a guard and a resolver prints names like these, in this order:
NavigationStartRoutesRecognizedGuardsCheckStartGuardsCheckEndResolveStartResolveEndActivationEndNavigationEnd
The events map onto the stages in the table:
NavigationStartmarks stage 1.RoutesRecognizedmarks the end of recognition.GuardsCheckStartandGuardsCheckEndbracket the guard stage.ResolveStartandResolveEndbracket the resolver stage.ActivationEndfollows route activation.NavigationEndends a successful navigation.
The router also emits ActivationStart, ChildActivationStart and ChildActivationEnd. Lazy routes add RouteConfigLoadStart and RouteConfigLoadEnd.
For a quick look without writing code, pass withDebugTracing() to provideRouter. It logs every event to the console. Remove it before you ship.
How a navigation can end
Every navigation finishes in exactly one of four ways, and each has its own event.
| Outcome | Event | Typical cause |
|---|---|---|
| Success | `NavigationEnd` | All checks passed and the route activated. |
| Cancelled | `NavigationCancel` | A guard returned `false`, a guard or resolver redirected, or a newer navigation replaced this one. |
| Error | `NavigationError` | A route did not match, a lazy chunk failed to load, or a resolver threw. |
| Skipped | `NavigationSkipped` | The target URL equals the current URL and `onSameUrlNavigation` is `'ignore'`, which is the default. |
NavigationCancel carries a code that tells you why it was cancelled. The cause can be a guard rejecting, a redirect, or a newer navigation taking over. Use it in a progress indicator or error logger to tell a rejected navigation apart from an abandoned one.
Redirects restart the pipeline
A redirect does not continue the current navigation. When a guard returns a UrlTree, the router cancels the current navigation and starts a new one to the target URL. The new navigation runs the full pipeline, including its own guards. A cancelled navigation followed by a fresh NavigationStart is therefore normal in the event log when a guard redirects.
A redirect can create a loop. If /login is itself protected by a guard that redirects back to a page that sends the user to /login, the router loops until it stops. Keep the redirect target outside the guarded routes.
Newer navigations win
The router handles one navigation at a time. If a second navigation begins while the first is still waiting, for example on a slow resolver, the router cancels the first. Its result is discarded and it ends in NavigationCancel. A user who clicks a link, changes their mind, and clicks another link does not end up on the first page.
This has two consequences for the code you write in later chapters:
- A guard or resolver that is still running when a navigation is superseded may finish its work, but its result is ignored. A resolver that uses RxJS and returns an Observable is unsubscribed from, so an in-flight HTTP request can be cancelled.
- Side effects in guards, such as writing to a service or logging, can happen for navigations that never complete. Keep guards free of side effects where you can, so a cancelled navigation leaves no trace.
Reading router state during a navigation
While a navigation is in flight, router.url still holds the old URL. router.getCurrentNavigation() returns details about the pending navigation, including the target URL and the trigger. It returns null when no navigation is running. The router publishes the new state only after activation. Guards and resolvers receive the pending route's snapshot as arguments, so they never need to read the router's current state.
Where guards and resolvers fit
With the stages in mind, the purpose of each hook is easier to see.
- Guards sit between "the router knows what the URL means" and "the router changes the screen". They answer a yes or no question, or redirect.
- Resolvers sit just before activation. They fetch data the next page needs, so the component starts with that data in hand.
- Neither hook runs after activation. Work that belongs after the page appears, such as loading secondary data, belongs in the component.
Exercise
A user clicks a link to a route that has a canActivate guard and a resolver. The guard returns a UrlTree pointing to /login. Does the resolver run, and how does the log of router events look?
Show answer
The resolver does not run, because guards run before resolvers and the redirect ends this navigation. The log shows NavigationStart, RoutesRecognized, GuardsCheckStart, then a NavigationCancel for the original navigation. A new navigation to /login then begins with its own NavigationStart and ends in NavigationEnd if /login allows it.
Exercise
While a resolver is waiting on a slow request, the user clicks a different link. What happens to the first navigation, and which event reports it?
Show answer
The router cancels the first navigation and starts the second. The first one ends with NavigationCancel. The result of the first resolver is ignored, and the router unsubscribes from the Observable it returned.