Open History to see the last commit
1import { QueryObserver } from '@tanstack/query-core'
2import { assertInInjectionContext, untracked } from '@angular/core'
3import { injectQueryZone } from './utils/inject-query-zone'
4import { injectBaseQuery } from './inject-base-query'
5import { signalProxy } from './utils/signal-proxy'
6import { queryResultFields } from './utils/result-fields'
7import type {
8 DefaultError,
9 QueryKey,
10 RefetchOptions,
11} from '@tanstack/query-core'
12import type {
13 CreateQueryOptions,
14 CreateQueryResult,
15 DefinedCreateQueryResult,
16} from './types'
17import type {
18 DefinedInitialDataOptions,
19 UndefinedInitialDataOptions,
20} from './query-options'
21β
22/**
23 * This overload is selected when `initialData` is set on the options returned by `optionsFn`, so the
24 * resulting `data` signal is never `undefined` (unless a `select` changes `TData` to include `undefined`).
25 *
26 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
27 * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like
28 * `queryClient.query`.
29 * @param optionsFn - A function returning the {@link DefinedInitialDataOptions} to use β everything you
30 * can pass to `injectQuery`, with `initialData` set. Similar to `computed` from Angular, this function runs
31 * in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.
32 * @returns The query result, typed so that `data` is never `undefined` (unless a `select` changes `TData` to
33 * include `undefined`).
34 *
35 * @example
36 * ```angular-ts
37 * @Component({
38 * selector: 'posts',
39 * template: `
40 * <!-- `postsQuery.data()` is `Post[]`, never `undefined`, thanks to `initialData` β even if a
41 * refetch fails, so the list stays visible alongside the error. -->
42 * @if (postsQuery.isError()) {
43 * <span>Error: {{ postsQuery.error()?.message }}</span>
44 * }
45 * <ul>
46 * @for (post of postsQuery.data(); track post.id) {
47 * <li>{{ post.title }}</li>
48 * }
49 * </ul>
50 * `,
51 * })
52 * export class Posts {
53 * readonly postsQuery = injectQuery(() => ({
54 * queryKey: ['posts'],
55 * queryFn: fetchPosts,
56 * initialData: [],
57 * }))
58 * }
59 * ```
60 */
61export function injectQuery<
62 TQueryFnData = unknown,
63 TError = DefaultError,
64 TData = TQueryFnData,
65 TQueryKey extends QueryKey = QueryKey,
66>(
67 optionsFn: () => DefinedInitialDataOptions<
68 TQueryFnData,
69 TError,
70 TData,
71 TQueryKey
72 >,
73): DefinedCreateQueryResult<TData, TError>
74β
75/**
76 * Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
77 *
78 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
79 * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like
80 * `queryClient.query`.
81 * @param optionsFn - A function returning the {@link UndefinedInitialDataOptions} to use β everything
82 * you can pass to `injectQuery`. Similar to `computed` from Angular, this function runs in the reactive
83 * context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.
84 * @returns The query result. `status()` is `'pending'` if there is no cached data to display, `'error'` if
85 * the last fetch attempt failed, or `'success'` if the query has data to display. `isPending`/`isSuccess`/
86 * `isError` are type-guard methods for convenience.
87 *
88 * @example
89 * ```angular-ts
90 * @Component({
91 * selector: 'posts',
92 * template: `
93 * @if (postsQuery.isPending()) {
94 * Loading...
95 * } @else if (postsQuery.isError()) {
96 * <span>Error: {{ postsQuery.error()?.message }}</span>
97 * } @else {
98 * <ul>
99 * @for (post of postsQuery.data(); track post.id) {
100 * <li>{{ post.title }}</li>
101 * }
102 * </ul>
103 * }
104 * `,
105 * })
106 * export class Posts {
107 * readonly postsQuery = injectQuery(() => ({
108 * queryKey: ['posts'],
109 * queryFn: fetchPosts,
110 * }))
111 * }
112 * ```
113 *
114 * @example
115 * Similar to `computed` from Angular, the function passed to `injectQuery` runs in the reactive context. In
116 * the example below, the query is automatically enabled and executed when the filter signal changes to a
117 * truthy value. When the filter signal changes back to a falsy value, the query is disabled.
118 * ```angular-ts
119 * @Component({
120 * selector: 'posts',
121 * template: `
122 * <input [ngModel]="filter()" (ngModelChange)="filter.set($event)" />
123 * @if (postsQuery.isPending()) {
124 * Loading...
125 * } @else if (postsQuery.isError()) {
126 * <span>Error: {{ postsQuery.error()?.message }}</span>
127 * } @else {
128 * <ul>
129 * @for (post of postsQuery.data(); track post.id) {
130 * <li>{{ post.title }}</li>
131 * }
132 * </ul>
133 * }
134 * `,
135 * })
136 * export class Posts {
137 * readonly filter = signal('')
138 *
139 * readonly postsQuery = injectQuery(() => ({
140 * queryKey: ['posts', this.filter()],
141 * queryFn: () => fetchPosts(this.filter()),
142 * enabled: !!this.filter(),
143 * }))
144 * }
145 * ```
146 */
147export function injectQuery<
148 TQueryFnData = unknown,
149 TError = DefaultError,
150 TData = TQueryFnData,
151 TQueryKey extends QueryKey = QueryKey,
152>(
153 optionsFn: () => UndefinedInitialDataOptions<
154 TQueryFnData,
155 TError,
156 TData,
157 TQueryKey
158 >,
159): CreateQueryResult<TData, TError>
160β
161/**
162 * This overload accepts the general {@link CreateQueryOptions} shape rather than the `initialData`-aware
163 * overloads above, so whether `data` is defined can't be inferred from the call site β useful when wrapping
164 * `injectQuery` in your own helper function that forwards caller-provided options.
165 *
166 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
167 * @param optionsFn - A function that returns query options. Similar to `computed` from Angular, this
168 * function runs in the reactive context, so signals read inside it drive the query.
169 * @returns The query result.
170 */
171export function injectQuery<
172 TQueryFnData = unknown,
173 TError = DefaultError,
174 TData = TQueryFnData,
175 TQueryKey extends QueryKey = QueryKey,
176>(
177 optionsFn: () => CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
178): CreateQueryResult<TData, TError>
179β
180export function injectQuery(
181 optionsFn: () => CreateQueryOptions,
182): DefinedCreateQueryResult | CreateQueryResult {
183 if (typeof ngDevMode === 'undefined' || ngDevMode) {
184 assertInInjectionContext(injectQuery)
185 }
186 const outsideZone = injectQueryZone()
187 const [resultSignal, getObserver] = injectBaseQuery(optionsFn, QueryObserver)
188 return Object.assign(signalProxy(resultSignal, queryResultFields), {
189 refetch: (options?: RefetchOptions) =>
190 outsideZone(() => untracked(() => getObserver().refetch(options))),
191 }) as unknown as DefinedCreateQueryResult | CreateQueryResult
192}