الانتقال إلى المحتوى
FrontendAngular· 7 دقائق للقراءة

httpResource Is for Reading Data, Not Saving It

A resource sends its request on its own, again whenever a signal it reads changes, and cancels the one still pending. Right for loading, wrong for a save.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Angular 22
محتويات المقال

A team moves its profile page to signals and likes how 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

The belief: 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.

It's an easy conclusion to reach. The request object accepts a 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

The resource guide describes a resource as a way to bring async data into signal-based code, and its loader as a function that "retrieves some state". An is a declaration: this component needs the data at this URL, for the current values of these signals. Angular decides when to send the request. A save is the opposite: an action the user decides to take, at one specific moment, exactly once.

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

The request function is tracked like a 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

"If a request is already pending, the resource cancels the outstanding request before issuing a new one." For a read, that's ideal: the older response is stale, so dropping it prevents a slow answer from overwriting a fresh one. For a write, cancelling only means the browser stops waiting. The request may already have reached the server and been saved, and now you have lost its response, its error and the knowledge of which version won. It's 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

The 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.

TypeScript profile-form.ts
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 }));  }}

In the right version, typing changes only the draft. The 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.

The rule is about intent, not the HTTP verb. A 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
When the request is sentAs soon as it's createdWhen you subscribe, or await firstValueFrom()
What sends it againAny signal it read changing, or reload()Only another call
A new request while one is pendingCancels the pending oneBoth run, unless you choose otherwise
Where the result goesIts value() signalWherever your handler puts it
FitsData the page showsSaves, deletes and other actions

How to apply it in your project

  1. Find resources that writeSearch for httpResource(, rxResource( and resource( and look for a method other than GET, or a loader that calls post, put, patch or delete.
  2. Move each write into a methodCall HttpClient from the event handler, such as a (click) or (ngSubmit), with subscribe() or firstValueFrom(), so a request goes out only when the user acts.
  3. Reconcile the read sideAfter a successful save, set() the returned entity or reload() the resource. On failure, leave the resource alone and show the error next to the form.
  4. Guard against double submitsDisable the button while a saving signal is true, or send clicks through exhaustMap when 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 PUT saves 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 with HttpClient from an event handler, then set() or reload() the resource.

📚 المصادر

  1. Reactive data fetching with httpResource — Angular
  2. Async reactivity with resources — Angular
  3. Making HTTP requests — Angular
  4. HttpResourceRef — Angular

التعليقات (0)