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