AI Hints
Home›Angular Tutorial›httpResource, Interceptors and Practice: A Books Client
Angular · Lesson 99 of 120

Practice: A Books Client

Your turn.

⏱ 2 min read▶ Video at 1:59:36🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Let's practise HTTP. You'll build a small client, that lists the books, and adds new ones to the server.

  • List the books
  • Add new ones
  • Your turn

A books client

Your turn. Pause the video, and try this. Load the books with HTTP resource. Add a title box, and an add button, that posts a new book. Then reload the list. Here is one solution. The resource loads the list. Add posts the new book, and reload asks the resource to fetch the list again. We added Middlemarch, and it got id five.

✍️ Exercise: A books client

Load /api/books with httpResource. An input + Add button POSTs { title, author: 'Unknown', price: 0 }, then calls books.reload().

Show hint

this.http.post('/api/books', book).subscribe(() => this.books.reload());

Show solution
app.tstypescript
import { Component, inject } from '@angular/core';
import { HttpClient, httpResource } from '@angular/common/http';
import { Book } from './book';

@Component({
  selector: 'app-root',
  template: `
    <input #t placeholder="New title"> <button (click)="add(t.value)">Add</button>
    @for (b of books.value(); track b.id) { <p>{{ b.id }}. {{ b.title }}</p> }
  `,
})
export class App {
  private http = inject(HttpClient);
  books = httpResource<Book[]>(() => '/api/books', { defaultValue: [] });
  add(title: string) {
    const book = { title, author: 'Unknown', price: 0 };
    this.http.post('/api/books', book).subscribe(() => this.books.reload());
  }
}

What module eleven taught

HTTP client sends requests, and returns observables. Get reads, while post, put, and delete change data. The error callback handles failures. HTTP resource turns requests into signals. And interceptors run for every request.

keyvalue
HttpClientget, post, put, delete
subscribe({ next, error })results and failures
httpResource()requests as signals
Interceptorsevery request

Summary

Your app can now talk to a real server. That's the end of module eleven. Next, more RxJS, and testing.

Key takeaways
  • HttpClient
  • httpResource
  • Interceptors
Next up: RxJS Basics — streams of values