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