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