
httpResource Is for Reading Data, Not Saving It
- كاتب موثّق
- Angular 22
محتويات المقال
httpResource() cleaned up the loading code, so the Save goes the same way: a PUT /api/profile whose body is the form's draft signal. In the Network panel, the page sends a PUT the moment it opens, before anyone has typed, carrying the empty draft. Then it sends one per keystroke, and most of them show up as canceled. The backend logs tell a different story: several of those canceled requests arrived and were saved, and the first one wiped the user's bio.
The common misconception
httpResource() is the signal-era replacement for HttpClient, so every call should become a resource, including the POST and PUT requests that save data. One API for everything feels cleaner than mixing Observables and signals in the same component.
method and a body, so a PUT type-checks and runs. The resource is built on HttpClient, so interceptors and auth headers apply as usual. It became stable in Angular 22, and the first manual test passes: you type, the request goes out, the data is saved. Nothing in the API says "reads only". The rules that make it unsuitable for writes are the same rules that make it so pleasant for reads, which is why they're easy to miss.
What actually happens
A resource describes data, not an action
It sends without waiting for anyone
HttpClient returns a : nothing goes out until something subscribes. The httpResource guide spells out the difference: it "initiates the request eagerly". A resource with method: 'PUT' sends its PUT when it's created, with whatever body the signals hold at that moment. In the opening story, that was an empty draft, sent before the profile had even loaded.
Every signal you read is a trigger
computed(). The guide says that whenever one of the signals it depends on changes, the resource "will emit a new http request". That includes the body. Read this.draft() there, and every keystroke is a save. Read a locale signal for a header, and switching the language saves again. You can bolt on a "submitted" signal and return undefined until the click, but then you're rebuilding a click handler out of reactive parts, and you still inherit the next rule.
Cancelling is right for reads and risky for writes
switchMap behavior built in, and you can't swap it for queueing or ignoring the second click.
reload() doesn't fit either. For a resource, it means "fetch this again", which for a PUT means "save again".
Read with a resource, write with HttpClient
httpResource guide is direct about it: "Avoid using httpResource for mutations like POST or PUT. Instead, prefer directly using the underlying HttpClient APIs." Keep the resource for the data the page shows, send the save from the event handler, and then tell the resource what changed.
import { httpResource } from '@angular/common/http';import { Component, signal } from '@angular/core';@Component({ selector: 'app-profile-form', template: `<input [value]="draft().bio" (input)="edit($event)" />`,})export class ProfileForm { readonly draft = signal<Profile>({ name: '', bio: '' }); // Sends a PUT on creation with the empty draft, then one per // keystroke; each new PUT cancels the one still pending readonly save = httpResource<Profile>(() => ({ url: '/api/profile', method: 'PUT', body: this.draft(), })); edit(event: Event) { const bio = (event.target as HTMLInputElement).value; this.draft.update((d) => ({ ...d, bio })); }}import { HttpClient, httpResource } from '@angular/common/http';import { Component, inject, signal } from '@angular/core';import { firstValueFrom } from 'rxjs';@Component({ selector: 'app-profile-form', template: `<button (click)="save()" [disabled]="saving()">Save</button>`,})export class ProfileForm { private readonly http = inject(HttpClient); // Reading: one GET when created; reload() fetches it again readonly profile = httpResource<Profile>(() => '/api/profile'); readonly draft = signal<Profile>({ name: '', bio: '' }); readonly saving = signal(false); // Writing: one PUT per click, sent now, and nothing cancels it async save() { this.saving.set(true); try { const req = this.http.put<Profile>('/api/profile', this.draft()); this.profile.set(await firstValueFrom(req)); // status(): 'local' } finally { this.saving.set(false); } }}PUT exists only inside save(), so it's sent once per click, and a failure rejects the await where you can handle it instead of disappearing into a canceled request. The saving signal disables the button, so an impatient double click can't send two saves. After success, set() puts the server's answer into the resource, and its status becomes local, the state the guide uses for a value that was set locally rather than loaded.
POST that only reads, such as a search endpoint that takes its filters in the body or a GraphQL query, behaves like a read and can live in a resource. A request that changes something on the server belongs to an event handler, whatever its verb.
httpResource() | HttpClient in a handler | |
|---|---|---|
await firstValueFrom() | ||
reload() | ||
value() signal | ||
How to apply it in your project
Find resources that write Search for httpResource(,rxResource(andresource(and look for amethodother thanGET, or a loader that callspost,put,patchordelete.Move each write into a method Call HttpClientfrom the event handler, such as a(click)or(ngSubmit), withsubscribe()orfirstValueFrom(), so a request goes out only when the user acts.Reconcile the read side After a successful save, set()the returned entity orreload()the resource. On failure, leave the resource alone and show the error next to the form.Guard against double submits Disable the button while a savingsignal is true, or send clicks throughexhaustMapwhen the save already lives in an RxJS stream.
Key takeaways
httpResource()sends eagerly, sends again when any signal it reads changes, and cancels the pending request.Those are rules for reading. A resource with a PUTsaves on creation and on every change to its body.Cancelling a write only stops the browser from waiting; the server may already have saved it. Load with httpResource(), save withHttpClientfrom an event handler, thenset()orreload()the resource.
التعليقات (0)