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