Blog

Part 30 · Capstone: A Reading-List App in Angular with Routing, Forms, HTTP and Tests

We build a small reading-list app in three steps, with routes, a signal store, httpResource, a pretend server in an interceptor and a Signal Forms page, then test the store and the routes.

This part puts the series together. We build a small reading-list app: a list of books, a page for each book, a page to add one, and a page for addresses that don’t exist. It uses the router from Part 16, a store like Part 15‘s, httpResource from Part 19, an interceptor from Part 18, a form from Part 21 and Part 22, and tests from Part 24 and Part 25.

We build it in three steps. Each step is the whole app so far, and each one adds to the last. 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. Start from a fresh ng new project, or delete the files from earlier parts first: a leftover page or spec file can break the build or change what ng test reports.

Try this first

A reading list has to save new books somewhere. Put this list in public/books.json:

[
  { "id": 1, "title": "Dune", "author": "Frank Herbert" },
  { "id": 2, "title": "Emma", "author": "Jane Austen" },
  { "id": 3, "title": "Holes", "author": "Louis Sachar" }
]

and this in src/app/app.ts. It reads the list, and its button sends a new book to /api/books with a POST, as in Part 18:

// src/app/app.ts
import { HttpClient, HttpErrorResponse, httpResource } from '@angular/common/http';
import { Component, inject, signal } from '@angular/core';

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

@Component({
  selector: 'app-root',
  template: `
    @if (books.hasValue()) {
      <p>{{ books.value().length }} books</p>
    }
    <button (click)="save()">Save a book</button>
    <p>{{ message() }}</p>
  `,
})
export class App {
  private readonly http = inject(HttpClient);
  protected readonly books = httpResource<Book[]>(() => '/books.json');
  protected readonly message = signal('');

  protected save() {
    const book = { title: 'Matilda', author: 'Roald Dahl' };
    this.http.post<Book>('/api/books', book).subscribe({
      next: (saved) => this.message.set(`Saved as book ${saved.id}`),
      error: (err: HttpErrorResponse) => this.message.set(`Save failed: ${err.status}`),
    });
  }
}

Before you read on, guess. Click Save a book. What does the page say?

Here’s what happens. The page shows:

3 books
Save a book
Save failed: 404

and the console has a red line:

Failed to load resource: the server responded with a status of 404 (Not Found)

Read the two together. The console line is the browser: it sent the POST, and the server answered 404, “nothing here”. The page line is our error callback, which got an HttpErrorResponse with status 404. The GET for /books.json worked, because that file exists.

ng serve is a development server. It hands out your app’s files and the files in public/. It can’t save anything, and it has no /api/books. A real app would talk to an API server that someone wrote, in any language, with a database behind it. We don’t have one. So in Step 2 we’ll write a pretend one, inside the app, as an interceptor. The rest of the app won’t know the difference.

The plan

Here are the files we’ll end up with:

public/books.json      the starting list
src/app/
  book.ts              the Book type
  book-store.ts        the store: loads books, adds a book
  fake-backend.ts      an interceptor that plays the server
  book-list.ts         /books
  book-detail.ts       /books/:id
  add-book.ts          /books/new, a Signal Forms page
  not-found.ts         every other address
  app.routes.ts        the routes
  app.config.ts        router and HttpClient setup
  app.ts               a menu and the router outlet
  book-store.spec.ts   tests for the store
  app.routes.spec.ts   tests for the routes

And here’s how they connect once the app is done:

App: menu + router-outlet the outlet shows one page at a time BookList /books BookDetail /books/:id AddBook /books/new NotFound ** BookStore books() has() add() private booksResource (httpResource) GET /api/books POST /api/books HttpClient fakeBackend interceptor public/ books.json GET answers POST itself (201) reads a signal calls an action request or update

Pages read the store and call its actions. Only the store talks to HttpClient, and only the interceptor knows there’s no server.

Read it from the top. The router picks one page. Pages never fetch anything themselves: they read signals from the store, and the add page calls the store’s add(). The store keeps its data in an httpResource, which is private. Every request goes through HttpClient and the interceptor, which plays the server.

Step 1: a store, the pages and their routes

Keep public/books.json from “Try this first”:

[
  { "id": 1, "title": "Dune", "author": "Frank Herbert" },
  { "id": 2, "title": "Emma", "author": "Jane Austen" },
  { "id": 3, "title": "Holes", "author": "Louis Sachar" }
]

Now the type. Put it in its own file, because the store, the pages and the tests all use it:

// src/app/book.ts
export interface Book {
  id: number;
  title: string;
  author: string;
}

export type NewBook = Omit<Book, 'id'>;

Omit<Book, 'id'> is TypeScript for “a Book without its id“: a title and an author. It’s what the add form will fill in. The server picks the id.

Next the store. It follows Part 15’s pattern: private state, public read-only signals, and methods for changes. The difference is where the state comes from. Instead of a signal we fill by hand, the private state is an httpResource that loads the list:

// src/app/book-store.ts
import { httpResource } from '@angular/common/http';
import { Service, computed } from '@angular/core';
import { Book } from './book';

@Service()
export class BookStore {
  private readonly booksResource = httpResource<Book[]>(() => '/books.json', { defaultValue: [] });

  readonly books = computed(() =>
    this.booksResource.hasValue() ? this.booksResource.value() : [],
  );
  readonly loading = this.booksResource.isLoading;
  readonly error = this.booksResource.error;
}

Some things to notice:

  • @Service() makes one store for the whole app. Every page that injects BookStore gets the same one, so the list loads once and stays loaded while you move between pages.
  • booksResource is private. No page can call set on it, or reload it at a bad moment.
  • books is a computed that checks hasValue() first. As Part 19 showed, reading value() while a resource is in its error status throws, even with a defaultValue. So pages get an empty list instead of an error.
  • loading and error hand out the resource’s own signals. They’re read-only Signals already, so pages can read them but not change them.

The list page reads the store. It shows a loading line, an error line or the list:

// src/app/book-list.ts
import { Component, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { BookStore } from './book-store';

@Component({
  selector: 'app-book-list',
  imports: [RouterLink],
  template: `
    <h1>Reading list</h1>
    @if (store.loading()) {
      <p>Loading...</p>
    } @else if (store.error()) {
      <p>Couldn't load your books.</p>
    } @else {
      <ul>
        @for (book of store.books(); track book.id) {
          <li>
            <a [routerLink]="['/books', book.id]">{{ book.title }}</a>
          </li>
        } @empty {
          <li>No books yet.</li>
        }
      </ul>
    }
  `,
})
export class BookList {
  protected readonly store = inject(BookStore);
}

The detail page gets its id from the URL as an input, as in Part 16’s user directory, and finds the book in the store:

// src/app/book-detail.ts
import { Component, computed, inject, input, numberAttribute } from '@angular/core';
import { BookStore } from './book-store';

@Component({
  selector: 'app-book-detail',
  template: `
    @if (book(); as b) {
      <h1>{{ b.title }}</h1>
      <p>by {{ b.author }}</p>
    } @else if (store.loading()) {
      <p>Loading...</p>
    } @else {
      <p>No book with id {{ id() }}.</p>
    }
  `,
})
export class BookDetail {
  protected readonly store = inject(BookStore);
  readonly id = input.required({ transform: numberAttribute });
  protected readonly book = computed(() => this.store.books().find((b) => b.id === this.id()));
}

The order of the branches matters. If you open /books/2 straight from the address bar, the store starts loading at that moment, and books() is empty. Without the loading() branch, the page would say “No book with id 2” until the list arrived.

// src/app/not-found.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-not-found',
  template: `<p>Page not found.</p>`,
})
export class NotFound {}
// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { BookDetail } from './book-detail';
import { BookList } from './book-list';
import { NotFound } from './not-found';

export const routes: Routes = [
  { path: '', redirectTo: 'books', pathMatch: 'full' },
  { path: 'books', component: BookList },
  { path: 'books/:id', component: BookDetail },
  { path: '**', component: NotFound },
];

redirectTo with pathMatch: 'full' sends the bare address / to /books, as in Part 17. The wildcard '**' comes last, because the router takes the first route that matches.

// 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()),
  ],
};
// 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="/books">My books</a>
    </nav>
    <router-outlet />
  `,
})
export class App {}

Open the app at localhost:4200. The address bar changes to /books, and the page shows:

My books
Reading list
Dune
Emma
Holes

Click Emma. The address bar says /books/2, and the page shows:

My books
Emma
by Jane Austen

Press Back, and you’re on /books again. Now try addresses that don’t fit. Type localhost:4200/books/9, then localhost:4200/shelves:

My books
No book with id 9.
My books
Page not found.

/books/9 matches books/:id, so the detail page handles it: the list loaded, and no book has that id. /shelves matches nothing but the wildcard.

Step 2: a pretend server

Now the app needs to save. As “Try this first” showed, there’s no server to save to. Part 18 had the answer: an interceptor doesn’t have to pass a request on. It can answer it itself.

This interceptor plays a small API at /api/books:

  • POST saves a book. It gives the book the next id, keeps it in memory, and answers with status 201 (“Created”) and the saved book.
  • GET returns every book. It reads public/books.json through the rest of the chain, as a real request, and adds the books saved since the page loaded.
  • Any other method or URL goes past it untouched.
// src/app/fake-backend.ts
import { HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { map, of } from 'rxjs';
import { Book, NewBook } from './book';

// There's no real server. This interceptor plays one for /api/books.
// Added books live in memory, so a page reload forgets them.
let added: Book[] = [];
let nextId = 101;

export const fakeBackend: HttpInterceptorFn = (req, next) => {
  if (req.url !== '/api/books') {
    return next(req);
  }
  console.log(`fake backend: ${req.method} /api/books`);
  if (req.method === 'POST') {
    const book: Book = { id: nextId++, ...(req.body as NewBook) };
    added = [...added, book];
    return of(new HttpResponse({ status: 201, body: book }));
  }
  return next(req.clone({ url: '/books.json' })).pipe(
    map((event) =>
      event instanceof HttpResponse
        ? event.clone({ body: [...(event.body as Book[]), ...added] })
        : event,
    ),
  );
};

New pieces:

  • of(new HttpResponse(...)) is Part 18’s trick. of makes an Observable that gives one value, here a response, and finishes. The request never leaves the app.
  • req.clone({ url: '/books.json' }) makes a copy of the request with a different address, and next sends the copy on. Requests can’t be changed, only copied (Part 18).
  • map is the RxJS operator from Part 20: it turns each value that comes through into a new one. Here, when the value is the response (instanceof HttpResponse), event.clone({ body }) makes a copy with the saved books added to the list. Other events pass through as they are.
  • The ids start at 101, so they can’t clash with the ids in the file.

The store now reads /api/books, and gets an action to add a book:

// src/app/book-store.ts
import { HttpClient, httpResource } from '@angular/common/http';
import { Service, computed, inject } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { Book, NewBook } from './book';

@Service()
export class BookStore {
  private readonly http = inject(HttpClient);
  private readonly booksResource = httpResource<Book[]>(() => '/api/books', { defaultValue: [] });

  readonly books = computed(() =>
    this.booksResource.hasValue() ? this.booksResource.value() : [],
  );
  readonly loading = this.booksResource.isLoading;
  readonly error = this.booksResource.error;

  has(title: string) {
    const wanted = title.trim().toLowerCase();
    return this.books().some((book) => book.title.toLowerCase() === wanted);
  }

  async add(newBook: NewBook): Promise<Book> {
    const saved = await firstValueFrom(this.http.post<Book>('/api/books', newBook));
    this.booksResource.update((books) => [...books, saved]);
    return saved;
  }
}
  • has(title) says whether a title is already on the list, ignoring case and spaces at the ends. The form will use it.
  • add sends the POST with HttpClient, not with the resource. A resource is for reading: Part 19 warned that a change to its params aborts a running load, and you don’t want that to happen to a save.
  • firstValueFrom from rxjs turns an Observable into a Promise of its first value, so add can await the answer. add is async, so it returns a Promise of the saved book. If the server answers with an error, the Promise rejects with the HttpErrorResponse, and so does add. The form in Step 3 catches it.
  • When the save works, booksResource.update(...) puts the saved book into the resource’s value, with a new array, as always. A resource changed like this has the status local. We could call reload() instead, and the fake GET would include the new book, but that’s a second request for something we already know. set and update cancel a running load too, which matters if someone saves before the list arrives (see Tips and traps).

Switch the interceptor on in app.config.ts:

// src/app/app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';
import { fakeBackend } from './fake-backend';

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

The pages don’t change. Open the app, click Emma, then My books. The page shows the same list as before:

My books
Reading list
Dune
Emma
Holes

and the console has one line:

fake backend: GET /api/books

One GET for three pages. The list page and the detail page both read the same app-wide store, and its resource loaded once.

When a real API exists, delete fake-backend.ts and remove it from withInterceptors. If the real server lives at the same address, nothing else changes. That’s the point of keeping every request in the store and every fake in one interceptor.

Step 3: the add-book form

The last page is a Signal Forms form, as in Parts 21 and 22. The model is a NewBook. Title and author are required, and a custom rule asks the store whether the title is already on the list:

// src/app/add-book.ts
import { Component, inject, signal } from '@angular/core';
import { form, FormField, FormRoot, required, validate } from '@angular/forms/signals';
import { Router } from '@angular/router';
import { NewBook } from './book';
import { BookStore } from './book-store';

@Component({
  selector: 'app-add-book',
  imports: [FormField, FormRoot],
  template: `
    <h1>Add a book</h1>
    <form [formRoot]="bookForm">
      <label>Title <input [formField]="bookForm.title" /></label>
      @let title = bookForm.title();
      @if (title.touched() && title.invalid()) {
        <p>{{ title.errors()[0].message }}</p>
      }
      <label>Author <input [formField]="bookForm.author" /></label>
      @let author = bookForm.author();
      @if (author.touched() && author.invalid()) {
        <p>{{ author.errors()[0].message }}</p>
      }
      @for (error of bookForm().errors(); track error.kind) {
        <p>{{ error.message }}</p>
      }
      <button type="submit" [disabled]="bookForm().submitting() || store.loading()">
        Add book
      </button>
    </form>
  `,
})
export class AddBook {
  protected readonly store = inject(BookStore);
  private readonly router = inject(Router);
  protected readonly model = signal<NewBook>({ title: '', author: '' });
  protected readonly bookForm = form(
    this.model,
    (p) => {
      required(p.title, { message: 'Enter a title' });
      validate(p.title, ({ value }) =>
        this.store.has(value()) ? { kind: 'duplicate', message: 'Already on your list' } : null,
      );
      required(p.author, { message: 'Enter an author' });
    },
    {
      submission: {
        action: async (fields) => {
          try {
            const saved = await this.store.add(fields().value());
            await this.router.navigate(['/books', saved.id]);
            return null;
          } catch {
            return { kind: 'server', message: "Couldn't save the book. Try again." };
          }
        },
      },
    },
  );
}

Most of this is Parts 21 and 22: one model signal, [formField] on each input, errors shown once a field is touched, and FormRoot running the submission action when the form is submitted. Two things are new together:

  • The validate rule reads this.store.has(...), which reads the store’s books() signal. A rule is reactive like a computed, so it runs again when the title changes or when the store’s list changes.
  • The action saves through the store, then uses Router.navigate to go to the new book’s page. ['/books', saved.id] is the same list of segments that [routerLink] takes.
  • If the save fails, store.add rejects, and catch turns that into an error returned from the action, as in Part 22. It has no fieldTree, so it lands on the whole form, and the @for over bookForm().errors() shows “Couldn’t save the book. Try again.” above the button. Without the catch, the page would sit on the form with an ERROR HttpErrorResponse in the console.
  • Add book is disabled while the store is still loading. The tips below explain why.

Now the routes. books/new must come before books/:id. The router takes the first match, and books/:id matches /books/new too, with new as the id. The add page also loads lazily with loadComponent, as in Part 16: the form code arrives only when someone opens it.

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { BookDetail } from './book-detail';
import { BookList } from './book-list';
import { NotFound } from './not-found';

export const routes: Routes = [
  { path: '', redirectTo: 'books', pathMatch: 'full' },
  { path: 'books', component: BookList },
  { path: 'books/new', loadComponent: () => import('./add-book').then((m) => m.AddBook) },
  { path: 'books/:id', component: BookDetail },
  { path: '**', 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="/books">My books</a>
      <a routerLink="/books/new">Add a book</a>
    </nav>
    <router-outlet />
  `,
})
export class App {}

Click Add a book, then Add book with both fields empty. submit touches every field and stops, so both errors show:

My booksAdd a book
Add a book
Title
Enter a title
Author
Enter an author
Add book

(The two menu links run together as My booksAdd a book, because links sit on one line and the page text joins them.) Type Dune in Title:

My booksAdd a book
Add a book
Title
Already on your list
Author
Enter an author
Add book

Now type Neuromancer in Title and William Gibson in Author, and click Add book. The address bar says /books/101, and the page shows:

My booksAdd a book
Neuromancer
by William Gibson

Click My books. The new book is on the list:

My booksAdd a book
Reading list
Dune
Emma
Holes
Neuromancer

The console shows each request that reached the pretend server:

fake backend: GET /api/books
fake backend: POST /api/books

Follow the save through the figure. The form called store.add. The store sent a POST through HttpClient. The interceptor answered with id 101. The store added the book to its resource, so books() changed, and every page that reads it is up to date. The router then showed the detail page, which found book 101 in the store. No page told another page anything.

Now reload the page at /books:

My booksAdd a book
Reading list
Dune
Emma
Holes

Neuromancer is gone. The pretend server kept it in a JavaScript variable, and a reload starts the app again from nothing. That’s the honest limit of a fake backend. Saving for real needs a server with a database.

Why no guard or resolver?

Part 17 had guards and resolvers. This app doesn’t need either. There’s no login, so there’s nothing for canActivate to protect. A resolver for the detail page would keep the old page on screen while the list loads; the store already loads it once, and the page shows “Loading…” meanwhile. A canDeactivate guard that warns before leaving a half-filled form would fit; Part 17’s section on canDeactivate shows how.

Worked example: testing the store

The store is the part every page depends on, so it gets the first test. It runs without the fake backend. In a test, provideHttpClientTesting() swaps the end of the chain for Part 25’s test backend, and the test plays the server:

// src/app/book-store.spec.ts
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { Book } from './book';
import { BookStore } from './book-store';

const BOOKS: Book[] = [
  { id: 1, title: 'Dune', author: 'Frank Herbert' },
  { id: 2, title: 'Emma', author: 'Jane Austen' },
];

describe('BookStore', () => {
  let store: BookStore;
  let httpTesting: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [provideHttpClient(), provideHttpClientTesting()],
    });
    store = TestBed.inject(BookStore);
    httpTesting = TestBed.inject(HttpTestingController);
    TestBed.tick();
    httpTesting.expectOne('/api/books').flush(BOOKS);
  });

  afterEach(() => {
    httpTesting.verify();
  });

  it('loads the books from /api/books', () => {
    expect(store.books().map((b) => b.title)).toEqual(['Dune', 'Emma']);
    expect(store.has(' dune ')).toBe(true);
  });

  it('adds a book with the id the server gives it', async () => {
    const adding = store.add({ title: 'Holes', author: 'Louis Sachar' });

    const req = httpTesting.expectOne({ method: 'POST', url: '/api/books' });
    expect(req.request.body).toEqual({ title: 'Holes', author: 'Louis Sachar' });
    req.flush({ id: 101, title: 'Holes', author: 'Louis Sachar' });

    const saved = await adding;
    expect(saved.id).toBe(101);
    expect(store.books().length).toBe(3);
  });
});

Run ng test --watch=false. The end of the output says:

✓ |lab| src/app/book-store.spec.ts (2 tests)
Test Files  1 passed (1)
     Tests  2 passed (2)

How it works:

  • beforeEach gets a fresh store, then does what Part 25 did for a resource: TestBed.tick() runs Angular’s pending work, which starts the load, and expectOne('/api/books').flush(BOOKS) answers it. Every test starts with a loaded store.
  • The first test reads signals straight away. A computed works its value out when you read it, so there’s nothing to wait for.
  • The second test calls add but doesn’t await it yet. The POST is waiting in the test backend, and the test checks the body before answering. Only after flush does it await adding, the Promise that add returned.
  • verify() in afterEach fails a test that leaves a request unanswered, or sends one too many.

The test talks to /api/books without knowing whether a fake or a real server will answer in the app. That’s the same promise the store makes to the pages.

Worked example: a route test that catches a wrong order

The second test file checks the routes, with Part 25’s RouterTestingHarness. It uses the real routes and the real pages, and answers the store’s GET with one book:

// src/app/app.routes.spec.ts
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { AddBook } from './add-book';
import { routes } from './app.routes';
import { BookDetail } from './book-detail';
import { NotFound } from './not-found';

describe('routes', () => {
  let httpTesting: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        provideRouter(routes, withComponentInputBinding()),
        provideHttpClient(),
        provideHttpClientTesting(),
      ],
    });
    httpTesting = TestBed.inject(HttpTestingController);
  });

  it('shows a book by its id', async () => {
    const harness = await RouterTestingHarness.create();
    const page = await harness.navigateByUrl('/books/2', BookDetail);
    httpTesting.expectOne('/api/books').flush([{ id: 2, title: 'Emma', author: 'Jane Austen' }]);
    await harness.fixture.whenStable();

    expect(page.id()).toBe(2);
    expect(harness.routeNativeElement?.textContent).toContain('Emma');
  });

  it('sends /books/new to the add page', async () => {
    const harness = await RouterTestingHarness.create();
    await harness.navigateByUrl('/books/new', AddBook);
  });

  it('shows the not-found page for unknown addresses', async () => {
    const harness = await RouterTestingHarness.create();
    await harness.navigateByUrl('/shelves', NotFound);
  });
});
Test Files  2 passed (2)
     Tests  5 passed (5)

The first test checks a whole path through the app: the URL, the route, the id as a number input (toBe(2), not '2'), the store and the rendered page. The other two look empty, but they aren’t. navigateByUrl(url, AddBook) fails the test if any other page ends up in the outlet. This file doesn’t call verify(): the add page’s store sends a GET that nobody answers, and checking the store’s requests is the store test’s job.

Now say a teammate tidies app.routes.ts and puts the two books/... routes the other way round:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { BookDetail } from './book-detail';
import { BookList } from './book-list';
import { NotFound } from './not-found';

export const routes: Routes = [
  { path: '', redirectTo: 'books', pathMatch: 'full' },
  { path: 'books', component: BookList },
  { path: 'books/:id', component: BookDetail },
  { path: 'books/new', loadComponent: () => import('./add-book').then((m) => m.AddBook) },
  { path: '**', component: NotFound },
];

It builds, and the browser console stays clean. ng test complains:

× sends /books/new to the add page
...
FAIL  |lab| src/app/app.routes.spec.ts > routes > sends /books/new to the add page
Error: Unexpected routed component type. Expected _AddBook but got _BookDetail
...
     36|   it('sends /books/new to the add page', async () => {
     37|     const harness = await RouterTestingHarness.create();
     38|     await harness.navigateByUrl('/books/new', AddBook);
...
Test Files  1 failed | 1 passed (2)
     Tests  1 failed | 4 passed (5)

Read it from the top:

  • × sends /books/new to the add page names the failing test. The sentence in it(...) is the first thing you see, which is why it should say what the app does.
  • Expected _AddBook but got _BookDetail is the harness. It navigated to /books/new and found the detail page in the outlet. (_AddBook is how the built code names AddBook.)
  • The numbered lines show where: line 38, the navigateByUrl call.

So books/:id caught /books/new first, with new as the id. Run the app with these routes and click Add a book. The page shows:

My booksAdd a book
No book with id NaN.

numberAttribute turned 'new' into NaN, as in Part 16. No error, no warning: only a test, or a confused reader, tells you. Put books/new back above books/:id, and both files pass again:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { BookDetail } from './book-detail';
import { BookList } from './book-list';
import { NotFound } from './not-found';

export const routes: Routes = [
  { path: '', redirectTo: 'books', pathMatch: 'full' },
  { path: 'books', component: BookList },
  { path: 'books/new', loadComponent: () => import('./add-book').then((m) => m.AddBook) },
  { path: 'books/:id', component: BookDetail },
  { path: '**', component: NotFound },
];
Test Files  2 passed (2)
     Tests  5 passed (5)

Two small test files cover a lot: the store’s loading and saving, the route list, the id input and the order of the routes. They don’t cover the form. A form test would set input values and dispatch events in jsdom, as Part 24 did with clicks; it’s a good next test to write.

Best practices

  • Keep every request in a store or service. Pages read signals and call actions. Swapping the fake backend for a real one, or the test backend in a test, then changes nothing in the pages. It replaces HttpClient calls scattered through components.
  • Load with a resource, save with HttpClient. The resource tracks loading and errors for reads; a method sends each change once, then updates the resource. It replaces a resource that you bend into sending POSTs.
  • Fake a missing server in one interceptor, and say it’s fake. One file, one comment, removed in one line when the API exists. It replaces fake data copied into every component.
  • Put specific routes above routes with parameters. books/new before books/:id, and '**' last. A route test pins the order down, which replaces finding out from a confused user.
  • Test the store and the routes first. They’re what every page depends on. A store test with HttpTestingController and a route test with RouterTestingHarness catch most wiring mistakes in a few lines.

Tips and traps

  • A detail page that says “not found” while loading. Opening /books/2 directly shows “No book with id 2” until the list arrives. Check loading() before you decide a book doesn’t exist.
  • Expecting a saved book to survive a reload. The fake backend keeps it in memory, so a reload forgets it. That’s the fake, not your store. Only a real server can save.
  • withComponentInputBinding() missing from a route test. The test’s provideRouter doesn’t read app.config.ts, so the id never reaches the input, and reading id() throws NG0950: Input "id" is required but no value is available yet. Pass the same features in the test.
  • Reading value() from the store’s resource without a check. It throws ResourceValueError once a load fails, even with a defaultValue. Expose a computed that checks hasValue() first, as books does.
  • Calling reload() right after a save. It works with this fake, but it’s a second request for a book you already have. Use update with the saved book.
  • Saving before the list has loaded. While the list loads, has('Dune') is false, so the duplicate check passes. Worse, the save’s update cancels the load that’s still running (Part 19), so the list ends up holding only the new book until a reload. That’s why Add book is disabled while store.loading() is true. In a real app, the server should refuse duplicates too.
  • A save that fails with nobody listening. firstValueFrom rejects with the HttpErrorResponse. If nothing catches it, the form just sits there and the console shows ERROR HttpErrorResponse. Catch it in the action and return an error for the form to show.

Pages read the store, the store talks to HttpClient, and only one interceptor knows the server is pretend.

Exercises

Exercise 1. Show how many books are on the list in the menu, as My books (3). Add a count to the store, and read it in App. After adding Neuromancer, the menu should say My books (4).

Exercise 2. The list page shows books in the order they were added. Show them sorted by title instead, in the store, so every page that wants a sorted list can have it. Watch out for Part 15’s trap with sort.

Exercise 3. Write a route test that checks that / redirects to /books. Hint: TestBed.inject(Router).url is the URL the router ended on.

Answers

1. count is a computed in the store, next to books:

// src/app/book-store.ts
import { HttpClient, httpResource } from '@angular/common/http';
import { Service, computed, inject } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { Book, NewBook } from './book';

@Service()
export class BookStore {
  private readonly http = inject(HttpClient);
  private readonly booksResource = httpResource<Book[]>(() => '/api/books', { defaultValue: [] });

  readonly books = computed(() =>
    this.booksResource.hasValue() ? this.booksResource.value() : [],
  );
  readonly count = computed(() => this.books().length);
  readonly loading = this.booksResource.isLoading;
  readonly error = this.booksResource.error;

  has(title: string) {
    const wanted = title.trim().toLowerCase();
    return this.books().some((book) => book.title.toLowerCase() === wanted);
  }

  async add(newBook: NewBook): Promise<Book> {
    const saved = await firstValueFrom(this.http.post<Book>('/api/books', newBook));
    this.booksResource.update((books) => [...books, saved]);
    return saved;
  }
}
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';
import { BookStore } from './book-store';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <nav>
      <a routerLink="/books">My books ({{ store.count() }})</a>
      <a routerLink="/books/new">Add a book</a>
    </nav>
    <router-outlet />
  `,
})
export class App {
  protected readonly store = inject(BookStore);
}

The page shows:

My books (3)Add a book
Reading list
Dune
Emma
Holes

Click Add a book, add Neuromancer by William Gibson, and the menu follows:

My books (4)Add a book
Neuromancer
by William Gibson

App now injects the store too, so the list starts loading as soon as the app starts, whatever page you open first.

2. Sort a copy. sort changes the array it’s called on, and books() is the resource’s own array, so [...this.books()] copies it first. localeCompare compares two strings the way a dictionary would:

// src/app/book-store.ts
import { HttpClient, httpResource } from '@angular/common/http';
import { Service, computed, inject } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { Book, NewBook } from './book';

@Service()
export class BookStore {
  private readonly http = inject(HttpClient);
  private readonly booksResource = httpResource<Book[]>(() => '/api/books', { defaultValue: [] });

  readonly books = computed(() =>
    this.booksResource.hasValue() ? this.booksResource.value() : [],
  );
  readonly sorted = computed(() =>
    [...this.books()].sort((a, b) => a.title.localeCompare(b.title)),
  );
  readonly count = computed(() => this.books().length);
  readonly loading = this.booksResource.isLoading;
  readonly error = this.booksResource.error;

  has(title: string) {
    const wanted = title.trim().toLowerCase();
    return this.books().some((book) => book.title.toLowerCase() === wanted);
  }

  async add(newBook: NewBook): Promise<Book> {
    const saved = await firstValueFrom(this.http.post<Book>('/api/books', newBook));
    this.booksResource.update((books) => [...books, saved]);
    return saved;
  }
}
// src/app/book-list.ts
import { Component, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { BookStore } from './book-store';

@Component({
  selector: 'app-book-list',
  imports: [RouterLink],
  template: `
    <h1>Reading list</h1>
    @if (store.loading()) {
      <p>Loading...</p>
    } @else if (store.error()) {
      <p>Couldn't load your books.</p>
    } @else {
      <ul>
        @for (book of store.sorted(); track book.id) {
          <li>
            <a [routerLink]="['/books', book.id]">{{ book.title }}</a>
          </li>
        } @empty {
          <li>No books yet.</li>
        }
      </ul>
    }
  `,
})
export class BookList {
  protected readonly store = inject(BookStore);
}

Add Brave New World by Aldous Huxley, then click My books. It’s first:

My books (4)Add a book
Reading list
Brave New World
Dune
Emma
Holes

3. Navigate to / and expect BookList, then check the URL:

// src/app/redirect.spec.ts
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { Router, provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { routes } from './app.routes';
import { BookList } from './book-list';

describe('the empty path', () => {
  it('redirects to /books', async () => {
    TestBed.configureTestingModule({
      providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()],
    });
    const harness = await RouterTestingHarness.create();
    await harness.navigateByUrl('/', BookList);
    expect(TestBed.inject(Router).url).toBe('/books');
  });
});
Test Files  3 passed (3)
     Tests  6 passed (6)

BookList injects the store, which sends its GET, so the test still needs provideHttpClientTesting() to keep that request inside the test. The test never answers it, because the URL is all it checks.

Where to go next

That’s the series. You can build an Angular 22 app from components and signals up to routes, forms, HTTP and tests, and you’ve seen each piece work in a browser.

The best next reading is the official documentation at angular.dev. Its guides go deeper on everything here, and its API reference is where to check a function’s exact options, as this series did against the installed packages. Some topics we left out, which you’ll meet in bigger apps:

  • A real backend. Any server that speaks HTTP and JSON works. Swap the fake interceptor out, and add authentication on the server, not only in guards.
  • Internationalization with @angular/localize, for apps in more than one language.
  • Angular Material and more of the CDK than Part 28 used, for ready-made, accessible widgets.
  • End-to-end tests that drive a real browser through the whole app, with a tool such as Playwright or Cypress.
  • Service workers for apps that work offline, with @angular/service-worker.
  • Deployment and build configuration, such as environment files and where to host the built dist/ folder.

Pick the one your next project needs, and read its guide on angular.dev with a small example open beside it, the way this series worked.

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.