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