Blog

Part 17 · Routing, Part 2: Guards, Resolvers, Child Routes and Titles

Guards decide whether a navigation may happen, and resolvers load data before a page appears. This part covers functional guards, resolvers read as inputs, child routes, redirects and page titles.

In Part 16 we gave an app several pages. provideRouter took a list of routes, routerLink moved between them, <router-outlet /> showed the matching page, and withComponentInputBinding() handed route parameters to the page as inputs. Every URL went straight to its page.

Real apps need a say in that. Some pages are only for people who have logged in. Some pages need data before they can show anything. Some pages sit inside other pages. This part covers guards, which decide whether a navigation may go ahead, resolvers, which load data first, child routes with a second outlet, redirects, and page titles. The guards use a store like the ones in Part 15. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.

Try this first

This app has two pages. The admin route has a canActivate list with one function in it. Paste the four files:

// src/app/pages.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  template: `<h1>Home</h1>`,
})
export class Home {}

@Component({
  selector: 'app-admin',
  template: `<h1>Admin</h1>`,
})
export class Admin {}
// src/app/app.routes.ts
import { CanActivateFn, Routes } from '@angular/router';
import { Admin, Home } from './pages';

const adminGuard: CanActivateFn = () => {
  console.log('adminGuard ran');
  return false;
};

export const routes: Routes = [
  { path: '', component: Home },
  { path: 'admin', component: Admin, canActivate: [adminGuard] },
];
// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <nav>
      <a routerLink="/">Home</a>
      <a routerLink="/admin">Admin</a>
    </nav>
    <router-outlet />
  `,
})
export class App {}
// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes, withComponentInputBinding()),
  ],
};

The config is the one from Part 16, with withComponentInputBinding() turned on. Every example in this part uses it.

Before you read on, guess. Click Admin. What does the page show, and what’s in the address bar?

Here’s what happens. The page shows:

HomeAdmin
Home

The address bar still says /, and the console has one line:

adminGuard ran

The link worked, and the router started a navigation to /admin. Before it showed the page, it ran adminGuard. The guard returned false, so the router cancelled the navigation. Nothing on the screen changed. (HomeAdmin is the two links running together, as inline elements do in the page text.)

A guard is a function the router asks

A guard is a function the router calls during a navigation. It answers one question: may this go ahead? You list guards on a route, and the router runs them before it changes the page.

CanActivateFn is the type of a guard that decides whether a route may be activated, which means shown. From the installed @angular/router, it reads:

type CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => MaybeAsync<GuardResult>;
type GuardResult = boolean | UrlTree | RedirectCommand;
type MaybeAsync<T> = T | Observable<T> | Promise<T>;

So a guard gets two arguments. route describes the route being entered: its parameters, its query parameters, its data. state.url is the whole URL the navigation is heading for. Our adminGuard ignored both, which TypeScript allows.

A guard can answer in three ways:

  • true: go ahead.
  • false: cancel. The reader stays where they were.
  • a UrlTree or a RedirectCommand: cancel, and go there instead. A UrlTree is the router’s own object for a URL. A RedirectCommand wraps a UrlTree and can add options for the new navigation.

MaybeAsync means the answer can also come later, as a Promise or an Observable (Part 20 covers Observables). The router waits for it.

There are four kinds of guard, one for each question:

On the route Type Asks
canActivate CanActivateFn May this route be shown?
canActivateChild CanActivateChildFn May a child of this route be shown?
canDeactivate CanDeactivateFn<T> May the reader leave this page?
canMatch CanMatchFn Should this route count as a match at all?

Each is a list. The router runs every guard in it, and all must say yes.

A guard that asks a store

Returning false isn’t much use. A real guard asks something: is anyone logged in? In Part 15 we kept shared state in a store, a service with a private signal and public read-only views. Here’s a tiny one for logging in:

// src/app/auth-store.ts
import { Service, computed, signal } from '@angular/core';

@Service()
export class AuthStore {
  private readonly userState = signal<string | null>(null);

  readonly user = this.userState.asReadonly();
  readonly loggedIn = computed(() => this.user() !== null);

  logIn(name: string) {
    this.userState.set(name);
  }

  logOut() {
    this.userState.set(null);
  }
}

string | null is a TypeScript union: the signal holds either a name or null, which means nobody.

The guard gets the store with inject(). A guard isn’t a component, but the router runs it in an injection context, the same kind of place as a component’s field initializers (Part 13). So inject() works at the top of the guard. It looks in the route’s injector and the app’s, not in any component’s providers:

// src/app/auth-guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthStore } from './auth-store';

export const authGuard: CanActivateFn = (route, state) => {
  const auth = inject(AuthStore);
  const router = inject(Router);
  if (auth.loggedIn()) {
    return true;
  }
  return router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
};

Router is the service behind routerLink. createUrlTree builds a UrlTree from the same kind of list routerLink takes, plus options. Here it makes /login with a returnUrl query parameter, so the login page knows where to send the reader afterwards.

The login page reads returnUrl as an input. That’s withComponentInputBinding() from Part 16: it fills inputs from query parameters too.

// src/app/login.ts
import { Component, inject, input } from '@angular/core';
import { Router } from '@angular/router';
import { AuthStore } from './auth-store';

@Component({
  selector: 'app-login',
  template: `
    <h1>Log in</h1>
    <button (click)="logIn()">Log in as Ana</button>
  `,
})
export class Login {
  readonly returnUrl = input<string>();
  private readonly auth = inject(AuthStore);
  private readonly router = inject(Router);

  protected logIn() {
    this.auth.logIn('Ana');
    this.router.navigateByUrl(this.returnUrl() ?? '/');
  }
}

navigateByUrl navigates from code, as if the reader had clicked a link to that URL. As Part 16 showed, a query parameter that isn’t in the URL sets its input to undefined, so a default like input('/') would never be used. input<string>() allows undefined, and ?? '/' means “or / if it’s undefined“.

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { authGuard } from './auth-guard';
import { Login } from './login';
import { Admin, Home } from './pages';

export const routes: Routes = [
  { path: '', component: Home },
  { path: 'login', component: Login },
  { path: 'admin', component: Admin, canActivate: [authGuard] },
];

pages.ts, app.ts and app.config.ts stay as they were. This time, type /admin straight into the address bar. The guard runs on that first navigation too. The address bar changes to /login?returnUrl=%2Fadmin, and the page shows:

HomeAdmin
Log in
Log in as Ana

%2F is how a / is written inside a query parameter. Click Log in as Ana. The address bar says /admin, and the page shows:

HomeAdmin
Admin

Now Home and Admin both work with no detour, because loggedIn() is true.

Why return a UrlTree instead of calling router.navigateByUrl('/login') inside the guard and returning false? Both end up on /login. But with a UrlTree, the router does the redirect itself, as its answer to this navigation. A guard that calls navigateByUrl starts a second navigation from inside the first, which cancels the first one halfway through. The guard’s own false is never even used.

A RedirectCommand does the same job and takes navigation options as a second argument. For example, new RedirectCommand(router.parseUrl('/login'), { replaceUrl: true }) redirects and replaces the current entry in the browser’s history. parseUrl turns a URL string into a UrlTree. We’ll need RedirectCommand for resolvers below.

canMatch: a route that isn’t there

canActivate lets the router match a route, then asks whether it may be shown. canMatch runs earlier. If it says no, the router acts as if the route wasn’t in the list, and keeps looking at the routes after it.

That suits pages a reader shouldn’t know exist. Add a reports route with canMatch, and a wildcard route at the end:

// src/app/pages.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  template: `<h1>Home</h1>`,
})
export class Home {}

@Component({
  selector: 'app-admin',
  template: `<h1>Admin</h1>`,
})
export class Admin {}

@Component({
  selector: 'app-reports',
  template: `<h1>Reports</h1>`,
})
export class Reports {}

@Component({
  selector: 'app-not-found',
  template: `<h1>Page not found</h1>`,
})
export class NotFound {}
// src/app/app.routes.ts
import { inject } from '@angular/core';
import { Routes } from '@angular/router';
import { authGuard } from './auth-guard';
import { AuthStore } from './auth-store';
import { Login } from './login';
import { Admin, Home, NotFound, Reports } from './pages';

const isLoggedIn = () => inject(AuthStore).loggedIn();

export const routes: Routes = [
  { path: '', component: Home },
  { path: 'login', component: Login },
  { path: 'admin', component: Admin, canActivate: [authGuard] },
  { path: 'reports', component: Reports, canMatch: [isLoggedIn] },
  { path: '**', component: NotFound },
];

isLoggedIn takes no arguments, so it fits any guard type. Type /reports into the address bar. The address bar keeps /reports, and the page shows:

HomeAdmin
Page not found

The reports route didn’t match, so the wildcard did. Log in first, and /reports shows Reports.

Another common use is two routes with the same path, each with its own canMatch: an admin dashboard and a normal one, both at /dashboard. The first one whose guards say yes wins.

canMatch also matters for lazy loading. Part 16’s loadComponent loads one component. Its sibling loadChildren loads a whole list of child routes, loadChildren: () => import('./admin.routes').then((m) => m.adminRoutes), so a feature’s routes and their providers live in their own chunk. The router downloads that list while it’s still matching. With loadChildren, a route that canMatch rejects never downloads its routes. canActivate runs too late to stop that download.

canDeactivate: leaving a page

The other direction matters too. A reader types into a form, then clicks a link by mistake. A canDeactivate guard runs before the router leaves the current page. Unlike the others, it gets the page’s component as its first argument, so it can ask the component.

// src/app/editor.ts
import { Component, computed, signal } from '@angular/core';

@Component({
  selector: 'app-editor',
  template: `
    <label>Note <input [value]="draft()" (input)="draft.set($event.target.value)" /></label>
    <button (click)="save()">Save</button>
    @if (hasUnsavedChanges()) {
      <p>Unsaved changes</p>
    }
  `,
})
export class Editor {
  protected readonly draft = signal('');
  private readonly saved = signal('');
  readonly hasUnsavedChanges = computed(() => this.draft() !== this.saved());

  protected save() {
    this.saved.set(this.draft());
  }
}

hasUnsavedChanges is public, without protected, because the guard reads it from outside the class.

// src/app/app.routes.ts
import { CanDeactivateFn, Routes } from '@angular/router';
import { Editor } from './editor';
import { Home } from './pages';

const unsavedGuard: CanDeactivateFn<Editor> = (editor) => !editor.hasUnsavedChanges();

export const routes: Routes = [
  { path: '', component: Home },
  { path: 'edit', component: Editor, canDeactivate: [unsavedGuard] },
];

CanDeactivateFn<Editor> is a generic (Part 3): it says the guard is for an Editor, so editor.hasUnsavedChanges() type-checks.

// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <nav>
      <a routerLink="/">Home</a>
      <a routerLink="/edit">Edit</a>
    </nav>
    <router-outlet />
  `,
})
export class App {}

Click Edit, type “Hi” into Note, and click Home. The address bar stays at /edit, and the page shows:

HomeEdit
Note Save
Unsaved changes

Click Save, then Home. This time the guard says yes, and you’re back on /:

HomeEdit
Home

Real apps often ask the reader instead of refusing. A guard can return the answer from the browser’s confirm() dialog:

const unsavedGuard: CanDeactivateFn<Editor> = (editor) =>
  !editor.hasUnsavedChanges() || confirm('Leave without saving?');

The browser’s Back button goes through the router too, and it has a catch. Start again: click Edit, type “Hi”, and press Back. The guard refuses, and the address bar stays at /edit. Now click Save and press Back again. You’d expect the home page. Instead the browser leaves the app, to the page you had open before it:

When the first Back was refused, the browser had already moved one step back in its history. The router put /edit back in the address bar by replacing that history entry, the one for /. So there’s no / to go back to. One router option makes it step forward again instead, which keeps the history as it was:

// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter, withComponentInputBinding, withRouterConfig } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(
      routes,
      withComponentInputBinding(),
      withRouterConfig({ canceledNavigationResolution: 'computed' }),
    ),
  ],
};

With 'computed', the same steps end where you’d expect:

HomeEdit
Home

Add it to any app with a canDeactivate guard. The rest of this part keeps it in app.config.ts.

A canDeactivate guard only covers navigations inside the app. Closing the tab or typing another site’s address doesn’t go through the router.

Resolvers: data before the page

A book page needs a book. The page could load it itself and show “Loading…” first. Or the router can load it before the page appears, so the page always has its data. A function that loads data for a route is a resolver.

The books live in two JSON files in public/:

{ "id": 1, "title": "Dune", "author": "Frank Herbert" }
{ "id": 2, "title": "Emma", "author": "Jane Austen" }

The resolver’s type is ResolveFn<T>. It gets the same two arguments as a guard, and returns the data, or a Promise of it:

// src/app/book.ts
import { ResolveFn } from '@angular/router';

export interface Book {
  id: number;
  title: string;
  author: string;
}

export const bookResolver: ResolveFn<Book> = async (route) => {
  const id = route.paramMap.get('id');
  const response = await fetch(`/books/${id}.json`);
  return response.json();
};

route.paramMap.get('id') reads the :id from the URL. fetch is the browser’s own way to load a URL, and async/await waits for it. Angular’s HttpClient is the usual tool, and Part 18 covers it; fetch keeps this part about the router.

The route lists the resolver under a key, here book:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { authGuard } from './auth-guard';
import { bookResolver } from './book';
import { BookPage } from './book-page';
import { Login } from './login';
import { Home } from './pages';

export const routes: Routes = [
  { path: '', component: Home },
  { path: 'login', component: Login },
  {
    path: 'books/:id',
    component: BookPage,
    canActivate: [authGuard],
    resolve: { book: bookResolver },
  },
];

With withComponentInputBinding(), resolved data goes to the input with the same name as the key. So BookPage has a book input, and it’s never empty:

// src/app/book-page.ts
import { Component, input } from '@angular/core';
import { Book } from './book';

@Component({
  selector: 'app-book-page',
  template: `
    <h1>{{ book().title }}</h1>
    <p>by {{ book().author }}</p>
  `,
})
export class BookPage {
  readonly book = input.required<Book>();
}
// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <nav>
      <a routerLink="/">Home</a>
      <a routerLink="/books/1">Book 1</a>
      <a routerLink="/books/2">Book 2</a>
    </nav>
    <router-outlet />
  `,
})
export class App {}

input.required (Part 5) is safe here. The router doesn’t create BookPage until the resolver has finished. Click Book 1. The guard sends you to the login page first. Click Log in as Ana, and the page shows:

HomeBook 1Book 2
Dune
by Frank Herbert

Click Book 2. The resolver runs again for the new :id, and the page shows Emma:

HomeBook 1Book 2
Emma
by Jane Austen

Here’s a click on Book 1 from the home page, once you’re logged in, step by step:

address bar route books/:id canActivate authGuard resolve bookResolver / /books/1 router-outlet Home BookPage AuthStore loggedIn: true true fetch books/1.json router waits… book: Dune input: Dune address bar still /; outlet shows Home guard passed; outlet still shows Home waiting for data; outlet still shows Home data ready: { book: Dune }; outlet still shows Home address bar /books/1; outlet shows Dune by Frank Herbert Click Book 1: the router matches /books/1 to the route books/:id canActivate: authGuard reads loggedIn() and returns true resolve: bookResolver fetches /books/1.json; the router waits The book arrives and is stored in the route's data as book BookPage is shown with its book input set; the URL updates

Guards run first, then resolvers. The page appears only when both have finished.

Here are those steps in words, in case the animation doesn’t play for you:

  1. You click Book 1. The router matches /books/1 to the route books/:id. The address bar still says /, and the outlet still shows Home.
  2. The router runs canActivate. authGuard reads loggedIn() from the store, which is true, so the guard returns true.
  3. The router runs the resolver. bookResolver fetches /books/1.json. The router waits, and the screen doesn’t change.
  4. The data arrives. The router stores it in the route’s data under the key book.
  5. The router creates BookPage, sets its book input, and shows it in the outlet. Only now does the address bar change to /books/1, as Part 16 showed: the router updates the URL when a navigation succeeds.

Guards always run before resolvers. If a guard says no, the resolver never runs and no data is loaded.

The wait in step 3 is the price. While a resolver runs, the old page stays on screen and nothing says that something is happening. For a quick load, that’s fine. For a slow one, load the data in the page instead and show a loading state; Part 19 does that with httpResource.

Child routes and a second outlet

An admin area has its own menu, and pages under it: /admin/users, /admin/settings. The menu stays while the page under it changes. That’s a child route: a route inside another route’s children, shown in a <router-outlet /> inside the parent’s component.

// src/app/admin.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-admin-layout',
  imports: [RouterLink, RouterOutlet],
  template: `
    <h1>Admin</h1>
    <nav>
      <a routerLink="users">Users</a>
      <a routerLink="settings">Settings</a>
    </nav>
    <router-outlet />
  `,
})
export class AdminLayout {}

@Component({
  selector: 'app-admin-users',
  template: `<p>Ana, Ben</p>`,
})
export class AdminUsers {}

@Component({
  selector: 'app-admin-settings',
  template: `<p>Nothing to set yet</p>`,
})
export class AdminSettings {}

The links say users, not /admin/users. Without the leading /, a routerLink is relative to the route of the component it’s in. AdminLayout belongs to /admin, so users means /admin/users.

// src/app/app.routes.ts
import { inject } from '@angular/core';
import { Routes } from '@angular/router';
import { AdminLayout, AdminSettings, AdminUsers } from './admin';
import { authGuard } from './auth-guard';
import { AuthStore } from './auth-store';
import { Login } from './login';
import { Home } from './pages';

export const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: () => (inject(AuthStore).loggedIn() ? '/admin' : '/home'),
  },
  { path: 'home', component: Home, title: 'Home' },
  { path: 'login', component: Login, title: 'Log in' },
  {
    path: 'admin',
    component: AdminLayout,
    canActivate: [authGuard],
    title: 'Admin',
    children: [
      { path: '', pathMatch: 'full', redirectTo: 'users' },
      { path: 'users', component: AdminUsers, title: 'Users' },
      { path: 'settings', component: AdminSettings },
    ],
  },
];
// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <nav>
      <a routerLink="/">Start</a>
      <a routerLink="/admin">Admin</a>
    </nav>
    <router-outlet />
  `,
})
export class App {}

Three new things are in the routes.

Child routes. admin has children. The router matches /admin/users in two steps: admin for AdminLayout, then users for AdminUsers, which goes into AdminLayout‘s outlet. The guard on admin covers every child, because no child can be shown without its parent.

A redirect. The empty child path redirects to users, so /admin on its own goes to /admin/users. pathMatch: 'full' means “only when nothing is left of the URL”. Why does { path: '', component: Home } not need it? A component route on '' with no children only matches when nothing is left of the URL. A redirect on '' would fire on every URL, so the router insists you choose. A redirectTo without a leading / is relative to the parent, like the links.

A redirect that decides. The top route’s redirectTo is a function. The router calls it in an injection context, like a guard, so it can inject() the store. It returns where to go: /admin for someone logged in, /home for everyone else.

Open the app at /. The address bar changes to /home. Click Admin, then Log in as Ana. The address bar says /admin/users, and the page shows:

StartAdmin
Admin
UsersSettings
Ana, Ben

Click Settings. Only the inner outlet changes:

StartAdmin
Admin
UsersSettings
Nothing to set yet

Click Start. You’re logged in now, so the function sends you to /admin, and the child redirect takes you on to /admin/users:

authGuard ran when you entered /admin, but not when you moved between its children: the parent route stayed active. To check every move between children, put a guard in the parent’s canActivateChild list instead. It runs each time a child is about to be shown.

Page titles

The routes above also have a title. When a navigation ends, the router sets the browser tab’s title, document.title, from the matched routes. It takes the deepest one that has a title. On /admin/users the tab says “Users”. On /admin/settings, which has no title, it says “Admin”, from the parent.

A title can be a function too, a ResolveFn<string>, when it depends on the URL. And if every title should have the same ending, you can replace the router’s title strategy, the service that does the setting. Here’s one that adds ” · Shop” and logs what it set:

// src/app/title-strategy.ts
import { Service, inject } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { RouterStateSnapshot, TitleStrategy } from '@angular/router';

@Service({ autoProvided: false })
export class ShopTitleStrategy extends TitleStrategy {
  private readonly title = inject(Title);

  override updateTitle(snapshot: RouterStateSnapshot) {
    const pageTitle = this.buildTitle(snapshot);
    this.title.setTitle(pageTitle ? `${pageTitle} · Shop` : 'Shop');
    console.log(`Title: ${this.title.getTitle()}`);
  }
}

It’s a service, so it’s marked with @Service(). autoProvided: false (Part 13) means nothing uses it until you list it. buildTitle is the router’s own rule, the deepest title, and Title is Angular’s service for document.title. To use the strategy, provide it in place of the router’s one, with useClass from Part 14:

// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import {
  TitleStrategy,
  provideRouter,
  withComponentInputBinding,
  withRouterConfig,
} from '@angular/router';
import { routes } from './app.routes';
import { ShopTitleStrategy } from './title-strategy';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(
      routes,
      withComponentInputBinding(),
      withRouterConfig({ canceledNavigationResolution: 'computed' }),
    ),
    { provide: TitleStrategy, useClass: ShopTitleStrategy },
  ],
};

Open the app, click Admin, Log in as Ana and Settings. The console shows:

Title: Home · Shop
Title: Log in · Shop
Title: Users · Shop
Title: Admin · Shop

The first line is the start: / redirected to /home. The last is /admin/settings, where the deepest title is the parent’s. The browser tab shows the same text. Most apps never need a custom strategy; a title on each route is enough.

Worked example: a book that isn’t there

The book page from earlier trusts that every book exists. Let’s give the app a link to a book with no file, and drop the guard to keep the example short:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { bookResolver } from './book';
import { BookPage } from './book-page';
import { Home, NotFound } from './pages';

export const routes: Routes = [
  { path: '', component: Home },
  { path: 'books/:id', component: BookPage, resolve: { book: bookResolver } },
  { path: 'not-found', component: NotFound },
];
// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <nav>
      <a routerLink="/">Home</a>
      <a routerLink="/books/1">Book 1</a>
      <a routerLink="/books/3">Book 3</a>
    </nav>
    <router-outlet />
  `,
})
export class App {}

Click Book 3. The page shows:

HomeBook 1Book 3
Home

Nothing happened, as far as the reader can see. The address bar still says /. The console has two red lines:

Failed to load resource: the server responded with a status of 404 (Not Found)
ERROR SyntaxError: Unexpected token 'N', "Not Found" is not valid JSON

Read them from the top:

  • Failed to load resource ... 404 (Not Found) is the browser. The fetch for /books/3.json got a 404: there’s no such file. fetch doesn’t treat a 404 as an error. It hands back the response, and response.ok is false.
  • Unexpected token 'N', "Not Found" is not valid JSON is our resolver. It called response.json() on the server’s text “Not Found”. That threw, and a resolver that throws stops the navigation with an error. That’s why the page didn’t change.

A resolver that can’t find its data should send the reader somewhere useful. A resolver can’t return a UrlTree for that: whatever it returns becomes the data. That’s what RedirectCommand is for; ResolveFn<T> may return T or a RedirectCommand. A first try:

// src/app/book.ts
import { inject } from '@angular/core';
import { RedirectCommand, ResolveFn, Router } from '@angular/router';

export interface Book {
  id: number;
  title: string;
  author: string;
}

export const bookResolver: ResolveFn<Book> = async (route) => {
  const id = route.paramMap.get('id');
  const response = await fetch(`/books/${id}.json`);
  if (!response.ok) {
    const router = inject(Router);
    return new RedirectCommand(router.parseUrl('/not-found'));
  }
  return response.json();
};

Click Book 3 again. Still nothing happens. The 404 line is back, and below it is a new error:

ERROR RuntimeError: NG0203: The `_Router` token injection failed. `inject()` function must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at https://v22.angular.dev/errors/NG0203

NG0203 says inject() ran outside an injection context. (_Router is how the built code names Router.) But a resolver runs in an injection context, so how? The context only lasts while the function runs synchronously, up to its first await. Our inject(Router) runs after await fetch(...). The router is still waiting for the resolver, but the injection context ended at the await.

The fix is the rule from guards: call inject() at the top, before any await:

// src/app/book.ts
import { inject } from '@angular/core';
import { RedirectCommand, ResolveFn, Router } from '@angular/router';

export interface Book {
  id: number;
  title: string;
  author: string;
}

export const bookResolver: ResolveFn<Book> = async (route) => {
  const router = inject(Router);
  const id = route.paramMap.get('id');
  const response = await fetch(`/books/${id}.json`);
  if (!response.ok) {
    return new RedirectCommand(router.parseUrl('/not-found'));
  }
  return response.json();
};

Click Book 3. The 404 still shows in the console, because the file really is missing. But now the address bar says /not-found, and the page shows:

HomeBook 1Book 3
Page not found

Worked example: a guard that returns a path

Here’s a shorter authGuard. It returns the path to the login page as a string:

// src/app/auth-guard.ts
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { AuthStore } from './auth-store';

export const authGuard: CanActivateFn = () => {
  const auth = inject(AuthStore);
  return auth.loggedIn() ? true : '/login';
};

The build stops:

✘ [ERROR] TS2322: Type '() => true | "/login"' is not assignable to type 'CanActivateFn'.
  Type 'true | "/login"' is not assignable to type 'MaybeAsync<GuardResult>'.
    Type '"/login"' is not assignable to type 'MaybeAsync<GuardResult>'. [plugin angular-compiler]

TypeScript explains it in three steps, each one narrower:

  • TS2322 means “this value doesn’t fit this type”. The first line: the whole function doesn’t fit CanActivateFn.
  • The second line says why: what it returns, true | "/login", doesn’t fit MaybeAsync<GuardResult>.
  • The third line names the culprit: "/login". TypeScript gives a string literal its own type, the exact text.

GuardResult is boolean | UrlTree | RedirectCommand. It has no string in it, so TypeScript refuses it. Turn the path into a UrlTree with parseUrl:

// src/app/auth-guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthStore } from './auth-store';

export const authGuard: CanActivateFn = () => {
  const auth = inject(AuthStore);
  const router = inject(Router);
  return auth.loggedIn() ? true : router.parseUrl('/login');
};

parseUrl('/login') is the string turned into the router’s UrlTree, so the build passes. To try it, guard the book route again:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { authGuard } from './auth-guard';
import { bookResolver } from './book';
import { BookPage } from './book-page';
import { Login } from './login';
import { Home, NotFound } from './pages';

export const routes: Routes = [
  { path: '', component: Home },
  { path: 'login', component: Login },
  {
    path: 'books/:id',
    component: BookPage,
    canActivate: [authGuard],
    resolve: { book: bookResolver },
  },
  { path: 'not-found', component: NotFound },
];

Click Book 1. The address bar says /login, and the page shows:

HomeBook 1Book 3
Log in
Log in as Ana

This shorter guard has lost the returnUrl, so after logging in, the login page sends you to /. The createUrlTree version from earlier keeps it.

In older code

Before functional guards, a guard was a class. You’ll see @Injectable({ providedIn: 'root' }) on a class that implements CanActivate, with a canActivate(route, state) method, and the route lists the class: canActivate: [AuthGuard]. Resolvers were classes that implement Resolve<Book>. The interfaces still exist, but listing a class in a route is deprecated. mapToCanActivate([AuthGuard]) turns such a class into a functional guard. Pages often read resolved data from inject(ActivatedRoute).data, an Observable, instead of an input. canLoad and CanLoad are deprecated; use canMatch.

Best practices

  • Write guards and resolvers as functions, and call inject() first. Get every service at the top, before any await. It replaces class guards with constructor injection, and avoids NG0203.
  • Redirect by returning a UrlTree or a RedirectCommand. The router cancels and redirects in one step. It replaces calling router.navigate inside a guard and returning false.
  • Read login state from a store’s signal. The guard and the header read the same loggedIn(), so they always agree. It replaces a guard that keeps its own flag.
  • Use canMatch for routes some readers shouldn’t know about, and canActivate for routes they should be sent to log in for. One falls through to other routes; the other cancels or redirects.
  • Give every route a title. The tab, the history and screen readers use it. It replaces setting document.title by hand in each page.
  • Use a resolver only for quick, essential data. The old page stays on screen while it runs. For slow data, load it in the page with a loading state (Part 19).

Tips and traps

  • A guard is the reader’s convenience, not your security. Anyone can change the JavaScript in their browser. The server must check every request for private data itself.
  • inject() after an await. NG0203 in the console, and the page doesn’t change. Move every inject() to the top of the function.
  • Returning a string from a guard. TS2322 at build time. Return router.parseUrl('/login') or router.createUrlTree([...]).
  • pathMatch left off an empty-path redirect. { path: '', redirectTo: 'users' } shows NG04014 in the console: please provide 'pathMatch'. The router rejects the whole route list, so no page shows. Add pathMatch: 'full'.
  • A resolver’s key and the input’s name don’t match. With resolve: { book: ... } and readonly data = input.required<Book>(), the router sets data to undefined, even though it’s required. data().title then throws TypeError: Cannot read properties of undefined. The key is the input’s name.
  • Back after a refused Back leaves the app. A canDeactivate guard refuses Back, the reader saves, presses Back again, and lands outside your app. The router restored the URL by replacing the history entry before it. Add withRouterConfig({ canceledNavigationResolution: 'computed' }).
  • Expecting a parent’s canActivate to run on every child. It runs when the parent route becomes active, not when you move between its children. Use canActivateChild for that.

Guards and resolvers run before the page does: a guard decides whether the reader gets there, and a resolver decides what the page starts with.

Exercises

Exercise 1. Book ids are numbers. Add a guard to the books/:id route from the last worked example, so that /books/abc goes to /not-found before the resolver fetches anything. Hint: Number('abc') is NaN, and Number.isInteger(NaN) is false.

Exercise 2. Add a settings area: /settings/profile shows “Your profile” and /settings/password shows “Change password”, under a heading “Settings” with links to both. /settings on its own should go to /settings/profile. With the ShopTitleStrategy still in place, the tab should say “Profile · Shop” and “Password · Shop”.

Exercise 3. Give the book page a title that names the book’s number: “Book 1” on /books/1. Hint: title can be a ResolveFn<string>.

Answers

1. The guard reads :id from its route argument, like the resolver does:

// src/app/app.routes.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router, Routes } from '@angular/router';
import { bookResolver } from './book';
import { BookPage } from './book-page';
import { Home, NotFound } from './pages';

const numericId: CanActivateFn = (route) => {
  const router = inject(Router);
  const id = Number(route.paramMap.get('id'));
  return Number.isInteger(id) ? true : router.parseUrl('/not-found');
};

export const routes: Routes = [
  { path: '', component: Home },
  {
    path: 'books/:id',
    component: BookPage,
    canActivate: [numericId],
    resolve: { book: bookResolver },
  },
  { path: 'not-found', component: NotFound },
];

Type /books/abc into the address bar. It changes to /not-found, and the page shows:

HomeBook 1Book 3
Page not found

There’s no 404 in the console this time. The guard said no, so the resolver never ran. Book 1 still works.

2. A layout component with its own outlet, two children, and an empty-path redirect:

// src/app/settings.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-settings',
  imports: [RouterLink, RouterOutlet],
  template: `
    <h1>Settings</h1>
    <nav>
      <a routerLink="profile">Profile</a>
      <a routerLink="password">Password</a>
    </nav>
    <router-outlet />
  `,
})
export class Settings {}

@Component({
  selector: 'app-profile',
  template: `<p>Your profile</p>`,
})
export class Profile {}

@Component({
  selector: 'app-password',
  template: `<p>Change password</p>`,
})
export class Password {}
// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { Home } from './pages';
import { Password, Profile, Settings } from './settings';

export const routes: Routes = [
  { path: '', component: Home, title: 'Home' },
  {
    path: 'settings',
    component: Settings,
    children: [
      { path: '', pathMatch: 'full', redirectTo: 'profile' },
      { path: 'profile', component: Profile, title: 'Profile' },
      { path: 'password', component: Password, title: 'Password' },
    ],
  },
];
// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <nav>
      <a routerLink="/">Home</a>
      <a routerLink="/settings">Settings</a>
    </nav>
    <router-outlet />
  `,
})
export class App {}

Click Settings. The address bar says /settings/profile. Click Password, and the page shows:

HomeSettings
Settings
ProfilePassword
Change password

With the ShopTitleStrategy from earlier still in app.config.ts, the console shows a title for each page:

Title: Home · Shop
Title: Profile · Shop
Title: Password · Shop

Inside Settings, the link profile is relative, so it means /settings/profile. The redirect is relative too.

3. A title function gets the same snapshot as a resolver:

// src/app/app.routes.ts
import { ResolveFn, Routes } from '@angular/router';
import { bookResolver } from './book';
import { BookPage } from './book-page';
import { Home } from './pages';

const bookTitle: ResolveFn<string> = (route) => `Book ${route.paramMap.get('id')}`;

export const routes: Routes = [
  { path: '', component: Home, title: 'Home' },
  {
    path: 'books/:id',
    component: BookPage,
    resolve: { book: bookResolver },
    title: bookTitle,
  },
];
// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <nav>
      <a routerLink="/">Home</a>
      <a routerLink="/books/1">Book 1</a>
    </nav>
    <router-outlet />
  `,
})
export class App {}

Click Book 1. The console shows:

Title: Home · Shop
Title: Book 1 · Shop

What’s next

Our book resolver used fetch and checked response.ok by hand. In Part 18, we’ll load data with Angular’s HttpClient: typed responses, interceptors that add something to every request, and errors.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.