Sub topic 12
Declarative HTTP with httpResource
This chapter assumes you know resource() with params and loader, signals, and the basics of HttpClient. httpResource applies the resource model to HTTP reads. It sits on top of HttpClient, so you don't write a loader yourself.
What httpResource is
httpResource is a function from @angular/common/http. You give it a function that describes a request. It reads the signals inside that function, sends the request through HttpClient, and returns a resource whose value, status, error, and isLoading are signals. When a signal read by the request function changes, the resource cancels the old request and sends a new one.
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()}`);
}The type argument <User> only describes what you expect. Nothing checks the response at runtime unless you add parse (covered below). Because the resource can be empty, value() has the type User | undefined.
Compared with resource(), three things change:
- You write a request instead of a
paramsfunction and aloader. - Cancellation is automatic. Angular unsubscribes from the underlying
HttpClientcall, so you never handle anabortSignal. - Interceptors,
HttpClientTesting, XSRF handling, and the transfer cache for server-side rendering all apply, because the call goes throughHttpClient.
Your application must provide the HTTP client, or the resource fails at runtime:
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
};Three forms of the request
The request function can return one of three things.
A URL string. This is the shortest form and sends a GET request. Use it when the URL is all you need.
A request object. Return an HttpResourceRequest when you need query parameters, headers, or another method. The url field is required.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Product {
id: number;
name: string;
}
@Component({
selector: 'app-product-search',
template: `
<input #box (input)="query.set(box.value)" placeholder="Search" />
<button (click)="page.set(page() + 1)">Next page</button>
@if (products.error()) {
<p>Search failed.</p>
} @else if (products.isLoading()) {
<p>Searching...</p>
} @else {
<ul>
@for (p of products.value() ?? []; track p.id) {
<li>{{ p.name }}</li>
}
</ul>
}
`,
})
export class ProductSearchComponent {
readonly query = signal('');
readonly page = signal(1);
readonly products = httpResource<Product[]>(() => ({
url: '/api/products',
params: { q: this.query(), page: this.page() },
headers: { 'X-Client': 'web' },
}));
}Here params means URL query parameters (?q=...&page=...). This differs from the params option of resource(), which holds the loader's input. The names collide, so read carefully.
undefined. If the function returns undefined, no request is sent and the resource stays idle. Use this to wait for input, as with dependent resources.
readonly selectedId = signal<number | undefined>(undefined);
readonly detail = httpResource<Product>(() => {
const id = this.selectedId();
return id === undefined ? undefined : `/api/products/${id}`;
});Other response types and parsing
By default Angular parses the body as JSON. Variants cover the other body types:
| Function | Value type | Use for | Column |
|---|---|---|---|
| `httpResource<T>()` | `T \ | undefined` | JSON |
| `httpResource.text()` | `string \ | undefined` | Plain text, CSV, HTML |
| `httpResource.blob()` | `Blob \ | undefined` | Images, downloads |
| `httpResource.arrayBuffer()` | `ArrayBuffer \ | undefined` | Binary data |
The parse option runs on the decoded body before it becomes value. Use it to validate the shape or convert types. If parse throws, the resource enters the error state. This works with any validation function, including one from a schema library.
import { signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Product {
id: number;
name: string;
}
function parseProduct(raw: unknown): Product {
const data = raw as Partial<Product> | null;
if (typeof data?.id !== 'number' || typeof data.name !== 'string') {
throw new Error('Unexpected product shape');
}
return { id: data.id, name: data.name };
}
const productId = signal(1);
export const product = httpResource(() => `/api/products/${productId()}`, {
parse: parseProduct,
});Here the type of value() comes from the return type of parse, so no type argument is needed. The defaultValue option works as in resource(). It makes value() always defined, which removes the ?. and ?? [] in templates.
Response metadata
Besides the body, an httpResource exposes signals for the response itself:
headers()returns the responseHttpHeaders, orundefinedbefore a response arrives.statusCode()returns the HTTP status number.progress()returns anHttpProgressEvent. It is only populated when the request object setsreportProgress: true.
readonly report = httpResource.blob(() => ({
url: '/api/report.pdf',
reportProgress: true,
}));
// In a template: report.progress()?.loaded and report.progress()?.totalStatus, errors, and the same state signals
httpResource has the same state signals as resource(): status(), isLoading(), error(), hasValue(), reload(), set(), update(), and asReadonly(). Everything from the earlier chapters on rendering states and refreshing carries over.
Two details matter for HTTP:
- A non-2xx response puts the resource in the error state.
error()holds anHttpErrorResponse, soerror()?.statusgives you the HTTP code. A 404 and a network failure both land here, and you tell them apart by that object. - In recent versions, reading
value()while the resource is in the error state throws. Checkerror()first, as the template above does, or guard withhasValue().
Choosing between the three resource functions
| Situation | Choose |
|---|---|
| A GET request whose URL or query depends on signals | `httpResource` |
| Interceptors, `HttpClientTesting`, or transfer cache must apply | `httpResource` or `rxResource` with `HttpClient` |
| You already have a service that returns an Observable | `rxResource` |
| The source is `fetch`, IndexedDB, a Web API, or a Promise | `resource` |
| You need to combine several calls or transform the stream | `rxResource` |
httpResource cannot express a request that needs several steps, such as fetching one item and then calling another API with its result. For that, chain two resources, or use rxResource with RxJS operators.
Timing and testing
The request is not sent when the resource is created. It is sent when Angular next runs effects, so a test that checks for the request right after construction finds nothing. In a test, provide provideHttpClient() and provideHttpClientTesting(), create the resource, run TestBed.tick(), and then call expectOne on the HttpTestingController.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient, httpResource } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { Injector, signal } from '@angular/core';
describe('httpResource', () => {
it('requests the user and exposes the value', () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
const http = TestBed.inject(HttpTestingController);
const injector = TestBed.inject(Injector);
const id = signal(1);
const user = TestBed.runInInjectionContext(() =>
httpResource<{ id: number; name: string }>(() => `/api/users/${id()}`, { injector }),
);
TestBed.tick();
http.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
TestBed.tick();
expect(user.value()?.name).toBe('Ada');
http.verify();
});
});Common mistakes
- Forgetting
provideHttpClient(). The resource then reports an error and no request is sent. - Calling
value()in the error state without checkingerror()first. - Reading signals outside the request function, for example storing
this.userId()in a variable at construction time. The resource only reacts to signals read inside the function. - Assuming
httpResource<User>validates the response. The type argument is a promise to the compiler, and onlyparseenforces it at runtime. - Using it for writes. A POST in a reactive request re-sends whenever any read signal changes.
Stability
httpResource is experimental in the releases that ship it. It first appeared in Angular 19.2, and the options were renamed in later versions. In some early releases the reactive input was called request, and it is params in resource() now. Check the API reference for your Angular version before copying code from older articles.
Exercise
A component has readonly id = signal<number | undefined>(undefined) and shows details for the selected item. Write the httpResource call so that no request is sent until id has a number, and the request goes to /api/items/{id}. What status does the resource have while id is undefined?
Show answer
readonly item = httpResource<Item>(() => { const id = this.id(); return id === undefined ? undefined : /api/items/${id}; }); Returning undefined from the request function means no request is sent, so the resource stays in the idle status and value() is undefined. When id is set, the function re-runs, returns a URL, and the request is sent.
Exercise
A teammate writes httpResource<User>(() => '/api/me') and says the response is validated as a User. Is that right? How would you make a malformed response put the resource into the error state?
Show answer
No. The type argument only tells the compiler what to expect, and nothing is checked at runtime. Pass a parse function in the options, for example { parse: parseUser }, where parseUser throws when the body does not have the expected fields. A throw inside parse moves the resource to the error state.