Open History to see the last commit
1---
2id: resource-api
3title: Resource API
4---
5β
6> IMPORTANT: `toResource` is experimental. Its API may change in minor and patch releases.
7> Pin `@tanstack/angular-query` to an exact version when using this feature.
8β
9Angular Query can convert any query result into an Angular
10[`Resource`](https://angular.dev/api/core/Resource)-compatible view with `toResource`. The query
11remains responsible for fetching and caching the server state while Angular APIs can consume the
12familiar Resource shape.
13β
14```ts
15import { Component, input } from '@angular/core'
16import { injectQuery, toResource } from '@tanstack/angular-query'
17β
18@Component({
19 selector: 'todo-detail',
20 template: `
21 @if (todo.hasValue()) {
22 <h1>{{ todo.value().title }}</h1>
23 }
24 `,
25})
26export class TodoDetail {
27 readonly id = input.required<number>()
28β
29 readonly todoQuery = injectQuery(() => {
30 const id = this.id()
31 return {
32 queryKey: ['todo', id],
33 queryFn: () => fetchTodo(id),
34 }
35 })
36β
37 readonly todo = toResource(this.todoQuery)
38}
39```
40β
41The Resource view exposes these fields:
42β
43| Field | Description |
44| ----------- | --------------------------------------------------------------------- |
45| `value` | The current query data |
46| `status` | The query state as an Angular `ResourceStatus` |
47| `error` | The current error, normalized to `Error` |
48| `isLoading` | Whether the query is loading or reloading |
49| `hasValue` | Whether a value is available |
50| `snapshot` | The current Resource state as one signal |
51| `reload` | Refetches when the query is stale and returns whether a fetch started |
52β
53Use the query's field signals and methods for normal application code. Use `toResource(query)` when
54an Angular API expects a Resource or when Resource terminology makes an integration clearer. Call
55`query.refetch()` instead of `resource.reload()` when you need an unconditional refetch.
56β
57## Errors
58β
59`value()` throws when the Resource's status is `error`. Read `hasValue()` before accessing it, or
60inspect `error()` and `snapshot()` to render an error state. A failed background refetch can leave
61cached data available through `query.data()` while the Resource is in its error state.
62β
63Resource errors are not automatically reported globally. See [Error handling](./guides/error-handling.md)
64for an opt-in `ErrorHandler` integration.
65β
66## Using Resource with Signal Forms
67β
68> Signal Forms integration requires Angular 21 or newer.
69β
70Angular Signal Forms'
71[`validateAsync`](https://angular.dev/guide/forms/signals/async-operations#custom-async-validation-with-validateasync)
72accepts a Resource factory. Passing `injectQuery(...)` to `toResource` lets async validation use
73Angular Query caching, request deduplication, cancellation, retries, and stale-time behavior.
74β
75The example below validates a username. The query is disabled while the field has no value, and the
76factory returns `toResource(query)`.
77β
78> In Angular 21, `validateAsync`'s `factory` requires a return type of `ResourceRef` while
79> the implementation works with the read-only `Resource` interface returned by `toResource`.
80> To use the integration, cast the result of `toResource` as
81> `toResource(query) as unknown as ResourceRef<T | undefined>` where `T` is the query's data type.
82β
83> The `debounce` option on `validateAsync` does not work with `toResource(query)` due to
84> an [upstream Angular issue](https://github.com/angular/angular/issues/70884). Use
85> [`debounce`](https://angular.dev/api/forms/signals/debounce) from `@angular/forms/signals`
86> on the field instead. This delays updates from the input to the form model by 300 ms;
87> blurring the field or submitting the form flushes the pending update immediately.
88β
89```ts
90import { Component, inject, signal } from '@angular/core'
91import {
92 FormField,
93 debounce,
94 form,
95 validateAsync,
96} from '@angular/forms/signals'
97import { injectQuery, toResource } from '@tanstack/angular-query'
98β
99type UsernameValidation = {
100 available: boolean
101}
102β
103@Component({
104 selector: 'registration-form',
105 imports: [FormField],
106 template: `<input [formField]="registrationForm.username" />`,
107})
108export class RegistrationForm {
109 private readonly users = inject(UserService)
110 readonly model = signal({ username: '' })
111β
112 readonly registrationForm = form(this.model, (path) => {
113 debounce(path.username, 300)
114β
115 validateAsync(path.username, {
116 params: ({ value }) => value().trim() || undefined,
117 factory: (username) =>
118 toResource(
119 injectQuery(() => {
120 const name = username()
121 return {
122 queryKey: ['username-availability', name],
123 enabled: !!name,
124 queryFn: (): Promise<UsernameValidation> =>
125 this.users.checkUsername(name!),
126 }
127 }),
128 ),
129 onSuccess: (result) =>
130 result?.available
131 ? null
132 : {
133 kind: 'usernameTaken',
134 message: 'Username is already taken',
135 },
136 onError: () => ({
137 kind: 'usernameUnavailable',
138 message: 'Could not check username availability',
139 }),
140 })
141 })
142}
143```
144β
145Calling `reloadValidation()` on the field refetches the query only when its cached data is stale.
146β
147## Comparison
148β
149Choosing between Angular's built-in
150[`resource`](https://angular.dev/guide/signals/resource) and TanStack Query depends on whether the
151operation is isolated async state or server state shared across the application.
152β
153This table focuses on built-in behavior and may not capture every custom implementation. Review
154both APIs for the needs of your application.
155β
156Feature/Capability Key:
157β
158- β
1st-class, built-in, and ready to use with no added configuration or code
159- π Supported through an additional package
160- πΆ Possible, but requires custom application code
161- π Not built in
162β
163| | Angular `resource` | TanStack Query |
164| --------------------------------------- | ---------------------------------------------- | ----------------------------------------------------- |
165| Reactive parameters and signal state | β
| β
|
166| Request cancellation | β
| β
|
167| Angular Resource interface | β
| β
Through `toResource(query)` |
168| Shared cache by data identity | π | β
Query keys identify cached data |
169| Request deduplication across components | π | β
For queries with the same key |
170| Stale and garbage-collection timing | πΆ | β
`staleTime` and `gcTime` |
171| Cache invalidation and updates | πΆ | β
`invalidateQueries` and `setQueryData` |
172| Retries and background refetching | πΆ | β
Including focus and reconnect refetching |
173| Mutations and optimistic updates | πΆ | β
`injectMutation` and QueryClient cache updates |
174| SSR | β
A resource can transfer its value with `id` | β
The complete query cache is hydrated automatically |
175| Persistence | πΆ | π Through the persistence package |
176β
177Angular `resource` is a good fit for a self-contained asynchronous task. It retains the value of
178its own instance and can transfer that value during SSR, but it does not provide a shared,
179query-keyed cache or coordinate invalidation and mutations across the application. Use TanStack
180Query for server data that is reused, cached, invalidated, mutated, retried, or persisted.