Resources
The Angular Resource API (stabilized in Angular 22) bridges asynchronous data fetching directly with Angular's synchronous signal graph. It automatically tracks reactive dependencies, cancels outdated in-flight requests, and exposes built-in signals for loading, data, and error states without manual RxJS subscriptions.
The Three Resource Flavors
Angular provides three functions tailored to different async sources, all returning a consistent ResourceRef signal interface:
resource()(@angular/core). The core primitive that accepts aparamssignal computation and an async Promise-basedloaderfunction (ideal forfetchor third-party SDKs).httpResource()(@angular/common/http). A specialized HTTP wrapper built onHttpClientthat takes a reactive URL or request object and supports interceptors, progress tracking, and schema validation.rxResource()(@angular/core/rxjs-interop). Accepts an RxJS Observablestreaminstead of a Promise loader, allowing you to keep existing Observable operators while exposing results as signals.
Important Scope Rule: Resources are designed strictly for read operations (
GET). For data mutations (POST,PUT,DELETE), continue usingHttpClientdirectly so in-flight updates are never accidentally aborted when signals change.
Before vs. Now: Reactive Data Fetching
Suppose you want to fetch a user profile whenever a userId signal changes, while displaying a loading spinner and handling errors cleanly.
Before: Manual RxJS + State Boilerplate (Angular 16 – 18)
Previously, you had to bridge signals to Observables using toObservable(), manage race conditions with switchMap(), manually track isLoading and error flags, and handle cleanup.
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { switchMap, map, catchError, startWith, of } from 'rxjs';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-profile-before',
template: `
<button (click)="nextUser()">Next User</button>
@if (state().loading) {
<p>Loading user...</p>
} @else if (state().error) {
<p>Error: {{ state().error }}</p>
} @else if (state().data; as user) {
<h3>{{ user.name }}</h3>
}
`
})
export class UserProfileBeforeComponent {
private http = inject(HttpClient);
userId = signal(1);
// Must convert signal -> Observable -> switchMap -> manual state wrapper -> signal
private userState$ = toObservable(this.userId).pipe(
switchMap(id =>
this.http.get<User>(`/api/users/${id}`).pipe(
map(data => ({ data, loading: false, error: null })),
startWith({ data: null, loading: true, error: null }),
catchError(err => of({ data: null, loading: false, error: err.message }))
)
)
);
state = toSignal(this.userState$, {
initialValue: { data: null, loading: true, error: null }
});
nextUser() {
this.userId.update(id => id + 1);
}
}
Now: Declarative httpResource() & resource() (Angular 22)
With httpResource(), Angular tracks this.userId() automatically, aborts any pending HTTP call if the user clicks rapidly, and provides .value(), .isLoading(), and .error() signals out of the box.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-profile-now',
template: `
<button (click)="nextUser()">Next User</button>
<button (click)="userResource.reload()">Refresh</button>
@if (userResource.isLoading()) {
<p>Loading user...</p>
} @else if (userResource.error()) {
<p>Failed to load user.</p>
} @else if (userResource.hasValue()) {
<h3>{{ userResource.value().name }}</h3>
}
`
})
export class UserProfileNowComponent {
userId = signal(1);
// Automatically re-fetches whenever userId() changes and cancels stale requests
userResource = httpResource<User>(() => `/api/users/${this.userId()}`);
nextUser() {
this.userId.update(id => id + 1);
}
}
(Note: If you use the general resource() function instead of httpResource(), you define params: () => this.userId() and an async loader: ({ params, abortSignal }) => fetch(...) that passes abortSignal to cancel stale requests.)
Key Improvements at a Glance
| Feature | Before (toObservable + switchMap) |
Now (resource() / httpResource()) |
|---|---|---|
| State Tracking | Manually wrap responses into { data, loading, error } objects. |
Built-in .value(), .isLoading(), .error(), and .status() signals. |
| Type Narrowing | Manual null checks on response data. | .hasValue() acts as a TypeScript type guard narrowing out undefined. |
| Request Cancellation | Requires explicit switchMap plumbing. |
Automatic cancellation via AbortSignal when params change or component destroys. |
| Manual Refetching | Requires adding a separate refresh$ Subject to combineLatest. |
Built-in .reload() method triggers a fresh fetch immediately. |
| Conditional Fetching | Requires filter() or returning EMPTY inside switchMap. |
Returning undefined from params keeps the resource idle without fetching. |
resource
The resource() function (imported from @angular/core) is the general-purpose primitive for Promise-based asynchronous data fetching, such as using the browser's native fetch() API or third-party SDKs. Unlike httpResource(), it requires you to explicitly define two functions: params (to track reactive signal dependencies) and loader (to execute the async work and return a Promise).
Complete resource() Example with fetch() and AbortSignal
This example demonstrates how resource() tracks a search query signal, skips fetching when the input is empty, and automatically cancels outdated network requests when the user types quickly.
import { Component, signal, resource } from '@angular/core';
interface Product {
id: number;
title: string;
price: number;
}
@Component({
selector: 'app-product-search',
template: `
<input
type="text"
placeholder="Search products (min 2 chars)..."
(input)="onSearch($event)"
/>
<button (click)="productsResource.reload()">Reload</button>
@if (productsResource.isLoading()) {
<p>Searching...</p>
} @else if (productsResource.error()) {
<p>Something went wrong while fetching products.</p>
} @else if (productsResource.hasValue()) {
<ul>
@for (item of productsResource.value(); track item.id) {
<li>{{ item.title }} - \${{ item.price }}</li>
} @empty {
<li>No matching products found.</li>
}
</ul>
}
`
})
export class ProductSearchComponent {
searchQuery = signal('');
productsResource = resource({
// 1. Reactive dependency tracker:
// Re-runs whenever searchQuery() changes.
// Returning `undefined` prevents the loader from running (status stays 'idle').
params: () => {
const query = this.searchQuery().trim();
return query.length >= 2 ? { query } : undefined;
},
// 2. Async loader function:
// Receives the resolved `params` value and an `abortSignal` for cancellation.
loader: async ({ params, abortSignal }) => {
const response = await fetch(
`https://dummyjson.com{encodeURIComponent(params.query)}`,
{ signal: abortSignal } // Automatically cancels stale in-flight requests
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
return data.products as Product[];
}
});
onSearch(event: Event) {
const value = (event.target as HTMLInputElement).value;
this.searchQuery.set(value);
}
}
How resource() Works Under the Hood
- Reactive
paramsFunction. Angular tracks any signal read insideparams. Whenever those signals change,paramsrecalculates and triggers theloaderwith the new parameter object. - Conditional Skipping (
undefined). Ifparamsreturnsundefined,resource()skips callingloaderand sets its.status()to'idle'. - Built-in Cancellation (
abortSignal). IfsearchQuerychanges while afetch()request is still pending, Angular triggersabortSignalto cancel the previous request before starting the new one. - Writable Local State. Because
resource()returns aWritableResource, you can update its local value optimistically usingthis.productsResource.set(...)orthis.productsResource.update(...)without waiting for a server round-trip.
rxResource
The rxResource() function (imported from @angular/core/rxjs-interop) bridges existing RxJS Observable streams into Angular's signal-based Resource API. Instead of a Promise-based loader, it uses a stream property that returns an Observable—automatically subscribing, canceling stale requests when parameters change, and exposing .value(), .isLoading(), and .error() as signals.
Complete rxResource() Example with RxJS Operators
Use rxResource() when you want to keep RxJS operators like retry(), catchError(), or forkJoin(), or when integrating with existing Observable-based services.
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { rxResource } from '@angular/core/rxjs-interop';
import { retry, delay, map } from 'rxjs';
interface UserPost {
id: number;
title: string;
}
@Component({
selector: 'app-user-posts',
template: `
<div>
<button (click)="prevUser()" [disabled]="userId() <= 1">Previous User</button>
<span> User ID: {{ userId() }} </span>
<button (click)="nextUser()">Next User</button>
<button (click)="postsResource.reload()">Refresh</button>
</div>
@if (postsResource.isLoading()) {
<p>Loading posts...</p>
} @else if (postsResource.error()) {
<p>Could not load posts after retries.</p>
} @else {
<ul>
@for (post of postsResource.value(); track post.id) {
<li>{{ post.title }}</li>
} @empty {
<li>No posts available.</li>
}
</ul>
}
`
})
export class UserPostsComponent {
private http = inject(HttpClient);
userId = signal(1);
postsResource = rxResource({
// 1. Reactive parameter tracker:
// Re-evaluates whenever userId() changes.
params: () => ({ id: this.userId() }),
// 2. Observable stream factory:
// Receives `params` and must return an Observable.
// Automatically unsubscribes/cancels if `params` changes before completion.
stream: ({ params }) => {
return this.http
.get<UserPost[]>(`https://typicode.com{params.id}/posts`)
.pipe(
retry(2), // Keep RxJS resilience operators
map(posts => posts.slice(0, 5))
);
},
// Optional: Prevents .value() from being `undefined` while loading
defaultValue: []
});
nextUser() {
this.userId.update(id => id + 1);
}
prevUser() {
this.userId.update(id => Math.max(1, id - 1));
}
}
Key Highlights of rxResource()
streamInstead ofloader. Whileresource()expects a Promise fromloader,rxResource()expects an Observable fromstream.- Continuous Multi-Value Emissions. Unlike
resource()(which resolves once per request),rxResource()is a streaming resource. If your Observable emits multiple values over time (such as a WebSocket stream,interval(), or Server-Sent Events),.value()updates reactively with every emission. - Automatic Unsubscription. Angular automatically unsubscribes from the inner Observable whenparamschanges or when the component is destroyed, eliminatingtakeUntilDestroyed()boilerplate. defaultValueOption. PassingdefaultValue: []narrows the type ofpostsResource.value()fromUserPost[] | undefinedtoUserPost[], letting you iterate directly with@forwithout null checks.
Choosing Between the Three Resource Functions
| Function | Package | Best Used For |
|---|---|---|
httpResource() |
@angular/common/http |
Standard HTTP GET requests using HttpClient. |
resource() |
@angular/core |
Promise-based async work (fetch(), IndexedDB, third-party SDKs). |
rxResource() |
@angular/core/rxjs-interop |
Existing RxJS services, multi-emission streams (WebSockets), or RxJS operators (retry, combineLatest). |
In modern Angular (v16–v22), you implement POST, PUT, PATCH, and DELETE mutations using HttpClient directly—not httpResource() or resource(). Because the Resource API automatically aborts in-flight requests whenever reactive dependencies change, using it for mutations risks canceling important database writes mid-flight.
Instead, the recommended pattern pairs httpResource() for reactive GET queries with HttpClient (wrapped in firstValueFrom() or RxJS) for imperatively triggered mutations.
Complete CRUD Example (httpResource + HttpClient)
This example uses httpResource() to display a list of tasks and HttpClient methods (post, put, patch, delete) to mutate data, updating the UI cleanly via optimistic updates or .reload().
typescript
import { Component, inject, signal } from '@angular/core';
import { HttpClient, httpResource } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
export interface Todo {
id: number;
title: string;
completed: boolean;
}
@Component({
selector: 'app-todo-manager',
template: `
<div>
<input #titleInput type="text" placeholder="New task..." />
<button (click)="addTodo(titleInput.value); titleInput.value = ''" [disabled]="isSaving()">
Add (POST)
</button>
</div>
@if (todosResource.isLoading()) {
<p>Loading tasks...</p>
} @else {
<ul>
@for (todo of todosResource.value(); track todo.id) {
<li>
<input
type="checkbox"
[checked]="todo.completed"
(change)="toggleTodo(todo)"
/>
<span [style.text-decoration]="todo.completed ? 'line-through' : 'none'">
{{ todo.title }}
</span>
<button (click)="renameTodo(todo)">Rename (PUT)</button>
<button (click)="deleteTodo(todo.id)">Delete (DELETE)</button>
</li>
}
</ul>
}
`
})
export class TodoManagerComponent {
private http = inject(HttpClient);
private apiUrl = 'https://typicode.com';
// Track mutation loading/error state with standard signals
isSaving = signal(false);
// 1. GET: Reactive read query via httpResource
todosResource = httpResource<Todo[]>(() => `${this.apiUrl}?_limit=5`, {
defaultValue: []
});
// 2. POST: Create a new item
async addTodo(title: string) {
if (!title.trim()) return;
this.isSaving.set(true);
try {
const created = await firstValueFrom(
this.http.post<Todo>(this.apiUrl, {
title,
completed: false,
userId: 1
})
);
// Update local resource signal immediately (or call this.todosResource.reload())
this.todosResource.update(todos => [created, ...todos]);
} finally {
this.isSaving.set(false);
}
}
// 3. PATCH: Partially update a specific field (e.g., toggling 'completed')
async toggleTodo(todo: Todo) {
const updatedStatus = !todo.completed;
// Optimistic UI update before server responds
this.todosResource.update(todos =>
todos.map(t => (t.id === todo.id ? { ...t, completed: updatedStatus } : t))
);
try {
await firstValueFrom(
this.http.patch<Todo>(`${this.apiUrl}/${todo.id}`, {
completed: updatedStatus
})
);
} catch {
// Revert on failure by re-fetching truth from server
this.todosResource.reload();
}
}
// 4. PUT: Replace the entire resource payload
async renameTodo(todo: Todo) {
const newTitle = prompt('Enter new title:', todo.title);
if (!newTitle || newTitle === todo.title) return;
const fullReplacement: Todo = {
...todo,
title: newTitle
};
const saved = await firstValueFrom(
this.http.put<Todo>(`${this.apiUrl}/${todo.id}`, fullReplacement)
);
this.todosResource.update(todos =>
todos.map(t => (t.id === saved.id ? saved : t))
);
}
// 5. DELETE: Remove an item
async deleteTodo(id: number) {
// Optimistically remove from UI
this.todosResource.update(todos => todos.filter(t => t.id !== id));
try {
await firstValueFrom(this.http.delete<void>(`${this.apiUrl}/${id}`));
} catch {
this.todosResource.reload();
}
}
}
Summary of HTTP Methods & Best Practices
| HTTP Method | HttpClient Call |
Purpose & Payload |
|---|---|---|
POST |
this.http.post<T>(url, body) |
Creates a new resource on the server and returns the created entity. |
PUT |
this.http.put<T>(url, fullBody) |
Replaces an existing resource completely; requires sending all fields. |
PATCH |
this.http.patch<T>(url, partialBody) |
Partially updates only the specified fields of an existing resource. |
DELETE |
this.http.delete<void>(url) |
Deletes the resource at the target URL. |
Key Modern Angular Patterns Used Here
firstValueFrom()Over.subscribe(). Converting single-emissionHttpClientObservables into Promises withfirstValueFrom()lets you use cleanasync/awaitandtry/catch/finallyblocks without worrying about manual unsubscription.- Writable Resource Updates (
.update()/.reload()). BecausehttpResource()returns aWritableResource, you can mutate its cached value locally via.update()for instant UI feedback, or call.reload()to re-fetch fresh data from the server after a write succeeds. - Fetch Backend by Default. Modern Angular configures
provideHttpClient(withFetch())by default, ensuringHttpClientuses the browser's nativefetchAPI under the hood while preserving Angular HTTP interceptors.
References
- https://medium.com/@mrahmedkhan019/angulars-resource-vs-rxresource-apis-11b203fda9a6
- https://www.angulararchitects.io/blog/streaming-resources-in-angular-19-2-details-and-semantics/
- https://www.angulararchitects.io/en/blog/angular-22-the-most-important-new-features-at-a-glance/
- https://www.youtube.com/watch?v=0Z6i6Xu1IVI
- https://www.youtube.com/watch?v=4IKtwCQelWU
- https://www.youtube.com/watch?v=RNNFdqnHvbE
- https://www.youtube.com/watch?v=zsjKFA0-YvE&t=1459