Sub topic 12
Declarative HTTP with httpResource
This chapter assumes you know Angular signals, HttpClient, and the resource and rxResource APIs from the earlier chapters. You should also be comfortable with provideHttpClient() in your application config.
What httpResource does
httpResource is a resource built for HTTP. You give it a reactive request. Angular reads the signals inside that request, sends the call through its HTTP stack, and sends it again when those signals change. The result has the same value, status, error, isLoading, and reload() members you already know.
Because it uses HttpClient internally, your interceptors run, and so do testing tools such as HttpTestingController. You do not write a loader, and you do not handle abortSignal yourself. Angular cancels the superseded request for you.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-http',
template: `<p>{{ user.value()?.name }}</p>`,
})
export class UserHttpComponent {
readonly userId = signal(1);
readonly user = httpResource<User>(() => `/api/users/${this.userId()}`);
}Changing userId changes the URL, so the resource requests the new user.
Request forms
The first argument can take two forms.
| Form | Example | Use it when |
|---|---|---|
| URL string | `() => '/api/users/' + id()` | A plain GET is enough |
| Request object | `() => ({ url: '/api/users', params: { page: page() } })` | You need a method, query params, headers, or a body |
The request object accepts url, method, params, headers, and body. As with resource, returning undefined from the request function keeps the resource idle. Use this to wait for an input that is not ready yet.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Product {
id: number;
title: string;
}
@Component({
selector: 'app-search',
template: `<p>{{ results.value()?.length ?? 0 }} results</p>`,
})
export class SearchComponent {
readonly query = signal('');
readonly results = httpResource<Product[]>(() =>
this.query() === ''
? undefined
: { url: '/api/products', params: { q: this.query() } },
);
}While query is empty, no request is sent and the status stays idle.
How it differs from resource and rxResource
resourcetakes a Promise-returning loader. It suitsfetchand other async APIs.rxResourcetakes a stream function that returns an Observable. It suits existing RxJS code.httpResourcetakes a request description instead of a function that performs the call. It is the shortest option for ordinary HTTP reads.
Parsing and validating responses
By default, httpResource parses the body as JSON and trusts your type argument. TypeScript does not check the server's response at runtime. The parse option lets you validate or transform the body before it becomes value.
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
}
function parseUser(raw: unknown): User {
const data = raw as Partial<User>;
if (typeof data.id !== 'number' || typeof data.name !== 'string') {
throw new Error('Unexpected user shape');
}
return { id: data.id, name: data.name };
}
export const userResource = httpResource(() => '/api/users/1', {
parse: parseUser,
});If parse throws, the resource enters the error state, and you handle it the same way as an HTTP failure.
Common mistakes
- Using it for writes.
httpResourceis meant for reads that fit the reactive model. A POST that saves a form should be sent withHttpClientdirectly, because a resource would send it again whenever its inputs change. - Forgetting the provider. Without
provideHttpClient(), the resource fails when it tries to send the request. - Assuming the type is checked. The type argument is a promise to the compiler, not a runtime check. Use
parsewhere the server is not under your control.
Exercise
A component has page = signal(1). Write the httpResource call that requests /api/items with the query parameter page set from the signal, and explain what happens when page changes to 2.
Show answer
httpResource<Item[]>(() => ({ url: '/api/items', params: { page: this.page() } })). Angular reads page inside the request function, so when it becomes 2 the resource cancels any request still in flight and sends a new GET for /api/items?page=2. The status moves to loading while the new request runs.