Subscribing, storing the result, tracking loading, and catching errors, is a lot of code for every request. HTTP resource does all of it for us, with signals.
HTTP resource takes a function, that returns the URL. It sends the request for us, and gives back signals. Value holds the data. Is loading is true while waiting. And error holds any failure.
One line creates the resource. Default value is an empty list, so the template always has an array. The template reads is loading, error, and value. Run it. One request was sent, and the books appeared, with no subscribe at all.
app.tstypescript
import { Component } from '@angular/core';import { httpResource } from '@angular/common/http';import { Book } from './book';@Component({ selector: 'app-root', template: ` @if (books.isLoading()) { <p>Loading...</p> } @if (books.error()) { <p class="error">Could not load the books.</p> } @for (b of books.value(); track b.id) { <p>{{ b.title }} · {{ b.author }}</p> } `,})export class App { books = httpResource<Book[]>(() => '/api/books', { defaultValue: [] });}
The URL function reads the q signal. So whenever q changes, the resource sends a new request, by itself. The input sets q on every key press. We type austen. Run it. Nearly every key press sent a new request, and the last one found only Emma. In module twelve, we'll wait for the user to stop typing.
app.tstypescript
import { Component, signal } from '@angular/core';import { httpResource } from '@angular/common/http';import { Book } from './book';@Component({ selector: 'app-root', template: ` <input (input)="q.set($any($event.target).value)" placeholder="Search"> @for (b of books.value(); track b.id) { <p>{{ b.title }} · {{ b.author }}</p> } `,})export class App { q = signal(''); books = httpResource<Book[]>(() => `/api/books?q=${this.q()}`, { defaultValue: [] });}
Output
API GET /api/books?q= → 200
API GET /api/books?q=a → 200
API GET /api/books?q=au → 200
API GET /api/books?q=aus → 200
API GET /api/books?q=auste → 200
API GET /api/books?q=austen → 200
HTTP resource sends requests for you, and gives value, is loading, and error, as signals. It even reloads when its URL signals change. Next, interceptors.