# resource, rxResource, httpResource and HttpClient — recipes

Stable since Angular v22.0 (experimental on v20/21 — prefer `toSignal()` there). Verified 2026-09 against https://angular.dev/guide/signals/resource, https://angular.dev/guide/http/http-resource, https://angular.dev/api/common/http/httpResource, https://angular.dev/api/core/rxjs-interop/rxResource, https://angular.dev/guide/http/setup.

## Import paths (get these right — the audit found them missing)

```ts
import { resource } from '@angular/core';
import { rxResource } from '@angular/core/rxjs-interop';
import { httpResource, HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
```

## Which one

| Situation | Use |
|---|---|
| GET that depends on signals (route param, filter) | `httpResource(() => url or request object)` — reactive, cancels stale requests, exposes headers/status |
| Async work that is not `HttpClient` (IndexedDB, SDK call, `fetch` with custom auth) | `resource({ params, loader })` — loader receives `abortSignal` |
| Loader that is an Observable pipeline (existing API service returning Observables) | `rxResource({ params, stream })` |
| Streaming values (WebSocket, SSE) | `resource({ params, stream })` |
| Mutations (POST/PUT/DELETE) | `HttpClient` method in a service; `firstValueFrom()` or `await` inside a store method; then `reload()` the resource or update its value locally |

## httpResource

```ts
readonly filters = signal<OrderFilters>({ status: 'open', page: 1 });

readonly orders = httpResource<Page<Order>>(() => ({
  url: '/api/orders',
  params: { status: this.filters().status, page: this.filters().page },
}), { defaultValue: { items: [], total: 0 } });
```

- Returns `HttpResourceRef<T>` with `value()`, `hasValue()`, `isLoading()`, `error()`, `status()` (`'idle' | 'loading' | 'reloading' | 'resolved' | 'error' | 'local'`), `statusCode()`, `headers()`, `reload()`, `set()`, `update()`.
- Return `undefined` from the request function to skip the request (`idle`), e.g. while an id is missing.
- `parse` validates the payload at the edge: `httpResource(() => url, { parse: orderSchema.parse })` (Zod/Valibot) — the parsed type becomes the value type.
- `httpResource.text()`, `.blob()`, `.arrayBuffer()` for non-JSON.
- Deduplication across components: create the resource once in a store/service and expose it; two components each calling `httpResource` make two requests.
- SSR: `transferCache: true` on the request object (or rely on `provideClientHydration()`'s transfer cache for GETs) so the browser does not refetch what the server already loaded — see `angular-ssr`.

### Template

```html
@if (orders.hasValue()) {
  @for (o of orders.value().items; track o.id) { <app-order-row [order]="o" /> } @empty { <p>No orders</p> }
} @else if (orders.error()) {
  <p role="alert">Could not load orders. <button (click)="orders.reload()">Retry</button></p>
} @else {
  <app-skeleton rows="5" />
}
```

`hasValue()` narrows the type so `value()` is non-undefined inside the branch; `isLoading()` is true during both `loading` and `reloading` — show a spinner without hiding stale data.

## resource

```ts
readonly userId = input.required<string>();
readonly user = resource({
  params: () => ({ id: this.userId() }),
  loader: async ({ params, abortSignal }) => {
    const res = await fetch(`/api/users/${params.id}`, { signal: abortSignal });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return (await res.json()) as User;
  },
});
```

`params` re-runs the loader whenever a signal it reads changes; the previous request is aborted through `abortSignal`. Use `defaultValue` to avoid `undefined` checks; `resource.set(v)` for optimistic local updates (`status() === 'local'`).

## rxResource

```ts
readonly orders = rxResource({
  params: () => this.filters(),
  stream: ({ params }) => this.api.list(params),   // Observable<Page<Order>>
});
```

## Writes and stores

```ts
@Service()
export class OrdersStore {
  private readonly api = inject(OrdersApi);
  readonly filters = signal<OrderFilters>({ status: 'open', page: 1 });
  readonly orders = httpResource<Page<Order>>(() => ({ url: '/api/orders', params: { ...this.filters() } }));
  readonly saving = signal(false);

  async close(id: string) {
    this.saving.set(true);
    try { await firstValueFrom(this.api.close(id)); this.orders.reload(); }
    finally { this.saving.set(false); }
  }
}
```

Components read `store.orders.value()`, call `store.close(id)`. Use NgRx SignalStore (`withState`, `withMethods`, `withEntities`, `rxMethod`) when the feature has many entities and methods — decision in `angular-architecture`.

## HttpClient setup and interceptors

```ts
// app.config.ts
provideHttpClient(withInterceptors([authInterceptor, errorInterceptor]), withXsrfConfiguration({ cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN' }))
```

- `fetch` is the default backend on v22; `withXhr()` opts back in and is discouraged on SSR. On v20 add `withFetch()` when running SSR.
- A functional interceptor is `(req, next) => next(req.clone({ setHeaders: { Authorization: … } }))`; keep them small and ordered (auth → base URL → error mapping → retry on idempotent GETs with backoff).
- Error normalisation: map `HttpErrorResponse` to a domain error once in an interceptor; components show `error()` from the resource, never raw messages.
- Cancel-on-change is automatic with resources; with manual `HttpClient` calls use `switchMap` on the param stream and `takeUntilDestroyed()`.

## v20/21 fallback

```ts
readonly orders = toSignal(this.route.paramMap.pipe(map(p => p.get('id')!), switchMap(id => this.api.get(id))), { initialValue: null });
```

Loading and error state must then be modelled by hand (a `signal<'loading' | 'error' | 'ok'>`), which is the main reason to move to v22 resources.
