Project: Models and Service
The foundations.
Every page needs two things. The shape of a book, and the basket. Let's build those first.
- The shape of a book
- The basket
- Build them first
book.ts
Book describes what the server sends. An id, a title, an author, and a price.
export interface Book {
id: number;
title: string;
author: string;
price: number;
}basket.ts
The list of books is private. Items, count, and total, are read-only signals. Add, remove, and clear, are the only ways to change it. Remove works by position, so the same book can be in the basket twice.
import { Service, signal, computed } from '@angular/core';
import { Book } from './book';
@Service()
export class Basket {
private readonly list = signal<Book[]>([]);
readonly items = this.list.asReadonly();
readonly count = computed(() => this.list().length);
readonly total = computed(() => this.list().reduce((sum, b) => sum + b.price, 0));
add(book: Book) { this.list.update(l => [...l, book]); }
remove(index: number) { this.list.update(l => l.filter((_, i) => i !== index)); }
clear() { this.list.set([]); }
}app.routes.ts
The empty path redirects to books. The book list loads straight away. The book page, basket, and checkout are lazy. And any unknown address goes back to the books.
import { Routes } from '@angular/router';
import { BookList } from './book-list';
export const routes: Routes = [
{ path: '', redirectTo: 'books', pathMatch: 'full' },
{ path: 'books', component: BookList },
{ path: 'books/:id', loadComponent: () => import('./book-page').then(m => m.BookPage) },
{ path: 'basket', loadComponent: () => import('./basket-page').then(m => m.BasketPage) },
{ path: 'checkout', loadComponent: () => import('./checkout').then(m => m.Checkout) },
{ path: '**', redirectTo: 'books' },
];The app shell
App injects the basket, and shows its count in the header. Below it, the router outlet shows the current page. We open the basket page. Run it. The header says basket nought, and the basket page is empty.
import { Component, inject } from '@angular/core';
import { RouterOutlet, RouterLink } from '@angular/router';
import { Basket } from './basket';
@Component({
selector: 'app-root',
imports: [RouterOutlet, RouterLink],
template: `
<nav class="bar">
<a id="home" routerLink="/books"><b>Page Turners</b></a>
<a id="cart" routerLink="/basket">Basket ({{ basket.count() }})</a>
</nav>
<router-outlet />
`,
styles: `.bar { display: flex; justify-content: space-between; margin-bottom: 8px; }`,
})
export class App {
basket = inject(Basket);
}Also uses book.ts
export interface Book {
id: number;
title: string;
author: string;
price: number;
}Also uses basket.ts
import { Service, signal, computed } from '@angular/core';
import { Book } from './book';
@Service()
export class Basket {
private readonly list = signal<Book[]>([]);
readonly items = this.list.asReadonly();
readonly count = computed(() => this.list().length);
readonly total = computed(() => this.list().reduce((sum, b) => sum + b.price, 0));
add(book: Book) { this.list.update(l => [...l, book]); }
remove(index: number) { this.list.update(l => l.filter((_, i) => i !== index)); }
clear() { this.list.set([]); }
}Also uses app.routes.ts
import { Routes } from '@angular/router';
import { BookList } from './book-list';
export const routes: Routes = [
{ path: '', redirectTo: 'books', pathMatch: 'full' },
{ path: 'books', component: BookList },
{ path: 'books/:id', loadComponent: () => import('./book-page').then(m => m.BookPage) },
{ path: 'basket', loadComponent: () => import('./basket-page').then(m => m.BasketPage) },
{ path: 'checkout', loadComponent: () => import('./checkout').then(m => m.Checkout) },
{ path: '**', redirectTo: 'books' },
];Also uses book-list.ts
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { RouterLink } from '@angular/router';
import { Book } from './book';
@Component({
selector: 'app-book-list',
imports: [RouterLink],
template: `
<input (input)="q.set($any($event.target).value)" placeholder="Search books">
@for (b of books.value(); track b.id) {
<p><a [routerLink]="['/books', b.id]">{{ b.title }}</a> · £{{ b.price }}</p>
} @empty { <p class="muted">No books found.</p> }
`,
})
export class BookList {
q = signal('');
books = httpResource<Book[]>(() => `/api/books?q=${this.q()}`, { defaultValue: [] });
}Also uses book-page.ts
import { Component, inject, input } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { Basket } from './basket';
import { Book } from './book';
@Component({
selector: 'app-book-page',
template: `
@if (book.error()) { <p class="error">Book not found.</p> }
@else if (book.value(); as b) {
<h2>{{ b.title }}</h2>
<p>by {{ b.author }} · £{{ b.price }} <button (click)="basket.add(b)">Add</button></p>
}
`,
})
export class BookPage {
basket = inject(Basket);
id = input.required<string>();
book = httpResource<Book>(() => `/api/books/${this.id()}`);
}Also uses basket-page.ts
import { Component, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { Basket } from './basket';
@Component({
selector: 'app-basket-page',
imports: [RouterLink],
template: `
<h2>Your basket</h2>
@for (b of basket.items(); track $index) {
<p>{{ b.title }} · £{{ b.price }}
<button (click)="basket.remove($index)">×</button></p>
} @empty { <p>Your basket is empty.</p> }
<p><b>Total: £{{ basket.total().toFixed(2) }}</b></p>
@if (basket.count()) { <a id="checkout" routerLink="/checkout">Go to checkout</a> }
`,
})
export class BasketPage {
basket = inject(Basket);
}Also uses checkout.ts
import { Component, inject, signal } from '@angular/core';
import { form, FormField, required, email } from '@angular/forms/signals';
import { Basket } from './basket';
@Component({
selector: 'app-checkout', imports: [FormField], templateUrl: './checkout.html',
})
export class Checkout {
basket = inject(Basket);
done = signal('');
model = signal({ name: '', email: '' });
checkout = form(this.model, p => {
required(p.name); required(p.email); email(p.email);
});
order() {
const paid = this.basket.total().toFixed(2);
this.done.set(`Thanks, ${this.model().name}! You paid £${paid}.`);
this.basket.clear();
}
}Also uses checkout.html
<h2>Checkout</h2>
@if (done()) {
<p class="card">{{ done() }}</p>
} @else {
<input [formField]="checkout.name" placeholder="Name">
<input [formField]="checkout.email" placeholder="Email">
<p>To pay: £{{ basket.total().toFixed(2) }}</p>
<button [disabled]="checkout().invalid()" (click)="order()">Place order</button>
}Also uses _url
/basketAlso uses _bar
1Summary
The book type, and the basket service, are the foundations. The app shell shows the header, and the current page. Next, the book list.
Key takeaways- Book
- Basket service
- App shell + routes