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 * @param optionsFn - A function returning the {@link DefinedInitialDataOptions} to use β everything you
26 * can pass to `injectQuery`, with `initialData` set. 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`).
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 `'pending'` if there is no cached data to display, `'error'` if
79 * the last fetch attempt failed, or `'success'` if the query has data to display. `isPending`/`isSuccess`/
80 * `isError` are type-guard methods for convenience.
81 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
82 * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like
83 * `queryClient.query`.
84 * @example
85 * ```angular-ts
86 * @Component({
87 * selector: 'posts',
88 * template: `
89 * @if (postsQuery.isPending()) {
90 * Loading...
91 * } @else if (postsQuery.isError()) {
92 * <span>Error: {{ postsQuery.error()?.message }}</span>
93 * } @else {
94 * <ul>
95 * @for (post of postsQuery.data(); track post.id) {
96 * <li>{{ post.title }}</li>
97 * }
98 * </ul>
99 * }
100 * `,
101 * })
102 * export class Posts {
103 * readonly postsQuery = injectQuery(() => ({
104 * queryKey: ['posts'],
105 * queryFn: fetchPosts,
106 * }))
107 * }
108 * ```
109 * @example
110 * Similar to `computed` from Angular, the function passed to `injectQuery` runs in the reactive context. In
111 * the example below, the query is automatically enabled and executed when the filter signal changes to a
112 * truthy value. When the filter signal changes back to a falsy value, the query is disabled.
113 * ```angular-ts
114 * @Component({
115 * selector: 'posts',
116 * template: `
117 * <input [ngModel]="filter()" (ngModelChange)="filter.set($event)" />
118 * @if (postsQuery.isPending()) {
119 * Loading...
120 * } @else if (postsQuery.isError()) {
121 * <span>Error: {{ postsQuery.error()?.message }}</span>
122 * } @else {
123 * <ul>
124 * @for (post of postsQuery.data(); track post.id) {
125 * <li>{{ post.title }}</li>
126 * }
127 * </ul>
128 * }
129 * `,
130 * })
131 * export class Posts {
132 * readonly filter = signal('')
133 *
134 * readonly postsQuery = injectQuery(() => ({
135 * queryKey: ['posts', this.filter()],
136 * queryFn: () => fetchPosts(this.filter()),
137 * enabled: !!this.filter(),
138 * }))
139 * }
140 * ```
141 */
142export function injectQuery<
143 TQueryFnData = unknown,
144 TError = DefaultError,
145 TData = TQueryFnData,
146 TQueryKey extends QueryKey = QueryKey,
147>(
148 optionsFn: () => UndefinedInitialDataOptions<
149 TQueryFnData,
150 TError,
151 TData,
152 TQueryKey
153 >,
154): CreateQueryResult<TData, TError>
155β
156/**
157 * This overload accepts the general {@link CreateQueryOptions} shape rather than the `initialData`-aware
158 * overloads above, so whether `data` is defined can't be inferred from the call site β useful when wrapping
159 * `injectQuery` in your own helper function that forwards caller-provided options.
160 * @param optionsFn - A function that returns query options. Similar to `computed` from Angular, this
161 * function runs in the reactive context, so signals read inside it drive the query.
162 * @returns The query result.
163 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
164 */
165export function injectQuery<
166 TQueryFnData = unknown,
167 TError = DefaultError,
168 TData = TQueryFnData,
169 TQueryKey extends QueryKey = QueryKey,
170>(
171 optionsFn: () => CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
172): CreateQueryResult<TData, TError>
173β
174export function injectQuery(
175 optionsFn: () => CreateQueryOptions,
176): DefinedCreateQueryResult | CreateQueryResult {
177 if (typeof ngDevMode === 'undefined' || ngDevMode) {
178 assertInInjectionContext(injectQuery)
179 }
180 const outsideZone = injectQueryZone()
181 const [resultSignal, getObserver] = injectBaseQuery(optionsFn, QueryObserver)
182 return Object.assign(signalProxy(resultSignal, queryResultFields), {
183 refetch: (options?: RefetchOptions) =>
184 outsideZone(() => untracked(() => getObserver().refetch(options))),
185 }) as unknown as DefinedCreateQueryResult | CreateQueryResult
186}