Sub topic 3
Reloading and cancelling stale requests
Prerequisites: you should know Angular components, signals, HttpClient, and basic HTTP methods.
Reloading and cancelling stale requests
An httpResource represents the latest request derived from its signals. Call reload() to repeat the current request, such as after clicking Refresh. When a request changes before the previous response arrives, Angular cancels the outdated request when possible. This prevents an older response from replacing newer data.
@Component({
selector: 'app-user',
template: `
<button (click)="user.reload()">Refresh</button>
@if (user.isLoading()) { <p>Loading...</p> }
<p>{{ user.value()?.name }}</p>
`,
})
export class UserComponent {
user = httpResource<User>(() => '/api/users/1');
}Parsing and validating responses
Use parse when the server response needs validation or transformation. Throw an error when the payload does not match the expected shape. The resource then exposes that error through error().
const user = httpResource<User>(
() => '/api/users/1',
{
parse: (raw: unknown) => {
const data = raw as Partial<User> | null;
if (!data || typeof data.id !== 'number' ||
typeof data.name !== 'string') {
throw new Error('Invalid user response');
}
return { id: data.id, name: data.name };
},
},
);Other response types
Use the matching variant when the response is not JSON:
httpResource.text(...)returns a string.httpResource.blob(...)returns aBlob, useful for files.httpResource.arrayBuffer(...)returns binary data.
HttpClient, interceptors, and mutations
httpResource builds on Angular's HttpClient, so configured interceptors still handle concerns such as authentication headers, logging, and retries. A resource is best for reading reactive data. Use HttpClient directly for writes because POST, PATCH, and DELETE represent user actions or commands.
rename(id: number, name: string) {
return this.http.patch(`/api/users/${id}`, { name });
}After a successful write, call reload() on a related resource if its displayed data is now stale.
Testing components
Test the component through Angular's HTTP testing tools. Trigger the resource, use HttpTestingController to expect its request, flush a valid or invalid response, and assert the template or resource state.
Exercise
What happens when a signal changes while an httpResource request is pending?
Show answer
Angular cancels the outdated request when possible and keeps the resource tied to the newest request.