r/angular • • 19d ago

Meet an Angular signal-based primitive for mutations (POST, PUT, DELETE & PATCH)

Every Angular dev has hand-rolled a "saving" boolean signal at some point, and it breaks on the first double-click: the first response resets it while the second request is still in flight.

Angular's resource API won't help, it's for reads only: it cancels in-flight requests, and cancelling a POST doesn't undo it on the server.

So I built @ngsignal/mutation, the write counterpart to resource:

readonly save = rxMutation<TodoDto, Todo>({
  mutationFn: (dto) => this.api.save(dto),
  concurrency: 'drop', // ignore clicks while saving
  onSuccess: () => this.todos.reload(),
});

Then you call it with the data to save, and read its pending, error and value signals straight from the template.

Need an upload with a progress bar? The HTTP variant takes a request description, just like httpResource does:

readonly uploadAvatar = httpMutation<File, User>({
  request: (file) => {
    const body = new FormData();
    body.append('avatar', file);
    return { 
      method: 'POST', url: '/api/avatar',
      body,
      reportProgress: true };
  },
});

And in the template:

@if (uploadAvatar.isPending() && uploadAvatar.uploadProgress(); as p) {
  <progress [value]="p.loaded" [max]="p.total"></progress>
}

Also:

  • 3 concurrency modes: run in parallel (default), queue calls in order, or drop clicks while one is in flight.
  • Never aborts a write that may already be on the server, and a late response can't overwrite newer state
  • Status code and response headers as signals, and SSR waits for in-flight writes

NgRx Toolkit and TanStack Query have mutations too. This one only depends on Angular core and sits next to resource: no store or query cache to adopt.

It's 0.x, so feedback on the API is very welcome before 1.0.

GitHub repo · Live demo on StackBlitz

23 Upvotes

3 comments sorted by

1

u/Taght 19d ago

Sounds nice, will give it a try.

1

u/Correct_Dinner_7458 19d ago

Thanks! Curious what you'd use it for: form submits, uploads, something else?
Any feedback is welcome.

0

u/[deleted] 19d ago

[deleted] — view deleted comment

5

u/Correct_Dinner_7458 19d ago

RxJS covers the async flow (exhaustMap, concatMap…), and if you're happy with that setup, you honestly don't need this.

What it adds is the state around a write, as signals: status / value / error / isPending

They are ready for templates, where only the latest call is allowed to update them. It also handles SSR (PendingTasks) and cleanup when the component is destroyed. That's the code everyone ends up rewriting by hand, usually with a saving flag that breaks on a double click.

Same reasoning as Angular shipping resource() even though RxJS could already handle reads. This is the write-side counterpart, since resource() is explicitly not meant for mutations.

And it doesn't compete with RxJS: rxMutation() takes any Observable, and httpMutation() goes through HttpClient.