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

resource-api.md

160 lines7.2 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```ts
76import { Component, inject, signal } from '@angular/core'
77import { form, validateAsync } from '@angular/forms/signals'
78import { injectQuery, toResource } from '@tanstack/angular-query'
79​
80type UsernameValidation = {
81 available: boolean
83​
84@Component({
85 selector: 'registration-form',
86 template: '',
87})
88export class RegistrationForm {
89 private readonly users = inject(UserService)
90 readonly model = signal({ username: '' })
91​
92 readonly registrationForm = form(this.model, (path) => {
93 validateAsync(path.username, {
94 debounce: 300,
95 params: ({ value }) => value().trim() || undefined,
96 factory: (username) =>
97 toResource(
98 injectQuery(() => {
99 const name = username()
100 return {
101 queryKey: ['username-availability', name],
102 enabled: !!name,
103 queryFn: (): Promise<UsernameValidation> =>
104 this.users.checkUsername(name!),
105 }
106 }),
107 ),
108 onSuccess: (result) =>
109 result?.available
110 ? null
111 : {
112 kind: 'usernameTaken',
113 message: 'Username is already taken',
114 },
115 onError: () => ({
116 kind: 'usernameUnavailable',
117 message: 'Could not check username availability',
118 }),
119 })
120 })
122```
123​
124Calling `reloadValidation()` on the field refetches the query only when its cached data is stale.
125​
126## Comparison
127​
128Choosing between Angular's built-in
129[`resource`](https://angular.dev/guide/signals/resource) and TanStack Query depends on whether the
130operation is isolated async state or server state shared across the application.
131​
132This table focuses on built-in behavior and may not capture every custom implementation. Review
133both APIs for the needs of your application.
134​
135Feature/Capability Key:
136​
137- βœ… 1st-class, built-in, and ready to use with no added configuration or code
138- 🟑 Partial support
139- 🟠 Supported through an additional package
140- πŸ”Ά Possible, but requires custom application code
141- πŸ›‘ Not built in
142​
143| | Angular `resource` | TanStack Query |
144| --------------------------------------- | ---------------------------------------------- | ----------------------------------------------------- |
145| Reactive parameters and signal state | βœ… | βœ… |
146| Request cancellation | βœ… | βœ… |
147| Angular Resource interface | βœ… | βœ… Through `toResource(query)` |
148| Shared cache by data identity | πŸ›‘ | βœ… Query keys identify cached data |
149| Request deduplication across components | πŸ›‘ | βœ… For queries with the same key |
150| Stale and garbage-collection timing | πŸ”Ά | βœ… `staleTime` and `gcTime` |
151| Cache invalidation and updates | πŸ”Ά | βœ… `invalidateQueries` and `setQueryData` |
152| Retries and background refetching | πŸ”Ά | βœ… Including focus and reconnect refetching |
153| Mutations and optimistic updates | πŸ”Ά | βœ… `injectMutation` and QueryClient cache updates |
154| SSR | βœ… A resource can transfer its value with `id` | βœ… The complete query cache is hydrated automatically |
155| Persistence | πŸ”Ά | 🟠 Through the persistence package |
156​
157Angular `resource` is a good fit for a self-contained asynchronous task. It retains the value of
158its own instance and can transfer that value during SSR, but it does not provide a shared,
159query-keyed cache or coordinate invalidation and mutations across the application. Use TanStack
160Query for server data that is reused, cached, invalidated, mutated, retried, or persisted.