Sub topic 2
Making an `httpResource` Request Depend on Signals
Assume you know Angular components, templates, signals, and basic HTTP concepts. An httpResource request function can read signals. Angular runs the function again when a signal it reads changes.
Reactive requests
In this example, changing userId creates a request for a different user:
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user',
template: `
<button (click)="next()">Next user</button>
<p>{{ user.value()?.name }}</p>
`,
})
export class UserComponent {
userId = signal(1);
user = httpResource<User>(() => `/api/users/${this.userId()}`);
next() {
this.userId.update((id) => id + 1);
}
}The call to this.userId() registers a dependency. When userId changes, Angular starts the new request. The resource manages the asynchronous state while the template reads its signals.
Waiting for input
Return undefined when the request should be idle. This is useful when a search should not run until the user enters text.
query = signal('');
results = httpResource<Product[]>(
() => {
const q = this.query().trim();
if (!q) {
return undefined;
}
return {
url: '/api/products',
params: { q, limit: '10' },
};
},
{ defaultValue: [] },
);An empty query sends no request. Once query contains text, the function returns a request and the resource fetches data.
Request objects
A request object describes more than a URL. It can contain method, query params, headers, and a request body.
save = httpResource(() => ({
url: '/api/preferences',
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: { theme: 'dark' },
}));Use query parameters for values in the URL query string. Use headers for metadata and body for data sent with methods such as POST or PUT.
Providing a default value
Before a response arrives, value() may be undefined. The defaultValue option supplies a value with the correct shape immediately. In the search example, the template can iterate over results.value() without checking for undefined.
httpResource is intended for reads driven by changing state. Use HttpClient directly for user-triggered writes such as saving or deleting data.
Exercise
How do you prevent an empty search query from sending a request?
Show answer
Return undefined from the resource's request function when the query is empty.