Sub topic 13
Writes and mutations: use HttpClient
This chapter assumes you know the basics of httpResource from the earlier chapters: declaring a resource, reading value(), isLoading() and error(), and calling reload(). It also assumes you know HTTP methods and RxJS Observable basics. By the end you will be able to decide when a request belongs in httpResource and when it belongs in HttpClient, and to wire the two together.
Reads and writes have different shapes
An httpResource describes data. You give it a function that returns a URL or request object, and Angular keeps the resource in sync with that description. The resource sends a request when the component is created and again when a signal read by the function changes. It also cancels a request that is no longer wanted. All of this suits reads, where the goal is "show the current state of this URL".
A write is a command. Something should happen once, because the user clicked a button, and not because a signal changed. The caller needs to know whether it succeeded, and usually needs to react to the outcome.
| Concern | Read with `httpResource` | Write with `HttpClient` |
|---|---|---|
| What triggers it | Signal changes, including at creation | An explicit call, such as a click handler |
| Repeat behavior | May run again whenever inputs change | Runs exactly once per call |
| Outdated requests | Cancelled when the request changes | Each call should complete on its own terms |
| Result | Signals: `value()`, `status()`, `error()` | An `Observable` you subscribe to or convert to a promise |
| Idempotency | Safe to repeat (GET) | POST and PATCH may not be safe to repeat |
Why a mutation in `httpResource` goes wrong
The request object accepts method and body, so the following compiles:
import { httpResource } from '@angular/common/http';
// Don't do this for a command.
const create = httpResource(() => ({
url: '/api/orders',
method: 'POST',
body: { sku: 'A-100', quantity: 1 },
}));It works technically, but it fails in several ways:
- It fires on its own. The resource sends the request when the component is created, so the POST happens before the user does anything. You can return
undefinedto hold it back, but then you need a signal acting as a trigger, and your "click" becomes a state change that the resource may re-interpret. - Changing inputs cancels it. If a signal the request function reads changes while the request is in flight, the resource aborts the previous request and sends a new one. For a GET that is the point. For a write, the browser has dropped the connection, but the server may already have processed the first request. A second POST can then create a duplicate.
reload()repeats it. Callingreload()re-sends the same request. On a read that is a refresh. On a write it is a second write.- The API models state, not completion. You get
value()andstatus(), but no clean way to say "when this specific call finishes, close the dialog". You end up watching signals with aneffect, which is harder to reason about than a promise or an observable.
httpResource is also exposed as a read API in its design. Use it for GET, and for the rare read that needs a body or custom method, such as a search endpoint that takes a POST body. Do not use it for anything that changes server state.
Writing with HttpClient
HttpClient methods return cold observables. Nothing is sent until someone subscribes. That matches the semantics a write needs: one subscription, one request.
A service keeps the write logic out of the component:
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
export interface User {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class UserService {
private http = inject(HttpClient);
rename(id: number, name: string) {
return this.http.patch<User>(`/api/users/${id}`, { name });
}
}The component calls the method when the user acts. Converting the observable to a promise with firstValueFrom makes the flow easy to read. It is safe here because an HTTP observable emits once and completes.
import { Component, inject, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
import { User, UserService } from './user.service';
@Component({
selector: 'app-user-editor',
template: `
@if (user.isLoading()) {
<p>Loading…</p>
}
@if (user.error()) {
<p>Could not load the user.</p>
}
<p>Current name: {{ user.value()?.name }}</p>
<input
[value]="draft()"
(input)="draft.set($any($event.target).value)"
/>
<button (click)="save()" [disabled]="saving() || !draft()">Save</button>
@if (saveError()) {
<p>{{ saveError() }}</p>
}
`,
})
export class UserEditorComponent {
private users = inject(UserService);
userId = signal(1);
user = httpResource<User>(() => `/api/users/${this.userId()}`);
draft = signal('');
saving = signal(false);
saveError = signal<string | null>(null);
async save() {
this.saving.set(true);
this.saveError.set(null);
try {
await firstValueFrom(this.users.rename(this.userId(), this.draft()));
this.user.reload();
} catch {
this.saveError.set('Saving failed. Try again.');
} finally {
this.saving.set(false);
}
}
}Three details matter here:
savingis a signal you own. A mutation has no built-in status, so you track it yourself. It also disables the button, which prevents double submits.reload()runs only after the write succeeds. The resource then asks the server for the fresh state, and the template updates through its signals.this.userId()is read when the click happens, not captured earlier. If the user switched records while the write was running, you would still want the id that was used for the request. For long operations, copy it to a localconstat the top ofsave().
The read-write cycle
The diagram shows who owns each step: the component triggers the write, HttpClient performs it, and httpResource refreshes the read.
Updating the local value without a reload
A reload costs a round trip, and the screen shows the old value until the response arrives. Resources are writable, so you can set the value yourself with set() or update(). This gives an optimistic update: show the expected result immediately, then correct it if the write fails.
async save() {
const previous = this.user.value();
this.user.update((u) => (u ? { ...u, name: this.draft() } : u));
try {
await firstValueFrom(this.users.rename(this.userId(), this.draft()));
} catch {
this.user.set(previous);
this.saveError.set('Saving failed. The change was reverted.');
}
}Be careful with this approach:
- While the value is set locally,
status()reportslocal, notresolved. Templates that check forresolvedwill treat the value differently. - If the user changes the signals that drive the request, the resource loads again and overwrites the local value. This is correct, since the id changed, but any pending optimistic state is lost.
- Prefer the plain
reload()flow unless the delay is noticeable. The server stays the single source of truth, and there is no rollback code to maintain.
Common mistakes
- Subscribing twice. Calling
subscribe()on the same observable twice, or using it with theasyncpipe andsubscribe(), sends two requests. Convert once, in one place. - Forgetting to subscribe.
this.users.rename(1, 'Ada');on its own sends nothing. The observable is cold. - Reloading too early. Calling
reload()before the write resolves fetches the old data. Put it after theawait, or inside thenextcallback. - Ignoring errors from the write. The resource's
error()signal only reflects the read. A failed PATCH never shows up there, so handle it where you made the call. - Missing
provideHttpClient(). BothhttpResourceandHttpClientneed it in the application config. Interceptors you register with it, such as an auth header interceptor, apply to reads and writes alike.
Choosing between the two
Ask what causes the request:
- If a signal change should cause it, and repeating it is harmless, use
httpResource. - If a user action or a program decision should cause it, and it changes data on the server, use
HttpClient. - If you need both, use both:
HttpClientfor the write, thenreload()on the related resource.
Exercise
A teammate writes httpResource(() => ({ url: '/api/cart/items', method: 'POST', body: { sku: this.sku() } })) to add an item to a cart whenever sku changes. Name two problems with this approach and describe the replacement.
Show answer
First, the resource sends the POST when the component is created, and again every time sku changes, so items are added without any user action. Second, when sku changes during an in-flight request, the resource cancels the old request and sends a new one, which can add duplicates because the server may have already handled the first. Calling reload() would also repeat the write. The replacement is a service method such as addItem(sku) that calls this.http.post('/api/cart/items', { sku }). The component calls it from a click handler, tracks a saving signal, and calls reload() on the cart httpResource after the request succeeds.
Exercise
After await firstValueFrom(this.users.rename(id, name)) succeeds, the page still shows the old name for a moment. Which two approaches remove the delay, and what is the trade-off of each?
Show answer
Calling reload() and waiting is the simple approach, but the old value stays visible until the GET returns. To remove the delay, use an optimistic update with user.update(...) before or right after the write. It shows the new name immediately, but you must restore the previous value with set() if the write fails, and the resource's status is local while the value is set manually. Both approaches keep the server as the source of truth if you finish with a reload().