httpMutation()

httpMutation(), from @ngsignal/mutation/http, is the counterpart of httpResource(): request returns a request description ({ method, url, body }) and the library sends it through HttpClient. That's why it also exposes statusCode, headers, uploadProgress and downloadProgress. A fake HttpInterceptorFn stands in for the server, with artificial delays. Source

Create user

Create a user, then submit an empty name to get a 422.

status
idle
statusCode
—
headers.get('Location')
—
error
protected readonly createUser = httpMutation<string, User, HttpErrorResponse>({
  request: (name) => ({ method: 'POST', url: '/api/users', body: { name } }),
});
@if (createUser.statusCode() === 422) {
  <p class="error-text" role="alert">The name is required.</p>
} @else if (createUser.isSuccess()) {
  <p class="hint" role="status">Created at {{ createUser.headers()?.get('Location') }}</p>
}

Upload with progress

protected readonly uploadAvatar = httpMutation<File, UploadedAvatar, HttpErrorResponse>({
  request: (file) => {
    const body = new FormData();
    body.append('avatar', file);
    return { method: 'POST', url: '/api/avatar', body, reportProgress: true };
  },
});
@if (uploadAvatar.isPending() && uploadAvatar.uploadProgress(); as p) {
  <div class="actions">
    <progress [value]="p.loaded" [max]="p.total ?? p.loaded" aria-label="Upload progress"></progress>
    <span>{{ p.total ? ((p.loaded / p.total) * 100 | number: '1.0-0') + '%' : p.loaded + ' bytes' }}</span>
  </div>
}