Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

resource-api.md

177 lines8.1 KB

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)
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
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 })
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.