Open History to see the last commit
1import {
2 DestroyRef,
3 ENVIRONMENT_INITIALIZER,
4 InjectionToken,
5 PLATFORM_ID,
6 computed,
7 effect,
8 inject,
9} from '@angular/core'
10import { QueryClient, noop, onlineManager } from '@tanstack/query-core'
11import { isPlatformBrowser } from '@angular/common'
12import { isDevMode } from './util/is-dev-mode/is-dev-mode'
13import type { Provider } from '@angular/core'
14import type {
15 DevtoolsButtonPosition,
16 DevtoolsErrorType,
17 DevtoolsPosition,
18 TanstackQueryDevtools,
19} from '@tanstack/query-devtools'
20​
21/**
22 * Usually {@link provideTanStackQuery} is used once to set up TanStack Query and the
23 * {@link https://tanstack.com/query/latest/docs/reference/QueryClient|QueryClient}
24 * for the entire application. Internally it calls `provideQueryClient`.
25 * You can use `provideQueryClient` to provide a different `QueryClient` instance for a part
26 * of the application or for unit testing purposes.
27 * @param queryClient - A `QueryClient` instance, or an `InjectionToken` which provides a `QueryClient`.
28 * @returns a provider object that can be used to provide the `QueryClient` instance.
29 */
30export function provideQueryClient(
31 queryClient: QueryClient | InjectionToken<QueryClient>,
32): Provider {
33 return {
34 provide: QueryClient,
35 useFactory: () => {
36 const client =
37 queryClient instanceof InjectionToken
38 ? inject(queryClient)
39 : queryClient
40 // Unmount the query client on injector destroy
41 inject(DestroyRef).onDestroy(() => client.unmount())
42 client.mount()
43 return client
44 },
45 }
46}
47​
48/**
49 * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
50 *
51 * Allows to configure a `QueryClient` and optional features such as developer tools.
52 *
53 * **Example - standalone**
54 *
55 * ```ts
56 * import {
57 * provideTanStackQuery,
58 * QueryClient,
59 * } from '@tanstack/angular-query-experimental'
60 *
61 * bootstrapApplication(AppComponent, {
62 * providers: [provideTanStackQuery(new QueryClient())],
63 * })
64 * ```
65 *
66 * **Example - NgModule-based**
67 *
68 * ```ts
69 * import {
70 * provideTanStackQuery,
71 * QueryClient,
72 * } from '@tanstack/angular-query-experimental'
73 *
74 * @NgModule({
75 * declarations: [AppComponent],
76 * imports: [BrowserModule],
77 * providers: [provideTanStackQuery(new QueryClient())],
78 * bootstrap: [AppComponent],
79 * })
80 * export class AppModule {}
81 * ```
82 *
83 * You can also enable optional developer tools by adding `withDevtools`. By
84 * default the tools will then be loaded when your app is in development mode.
85 * ```ts
86 * import {
87 * provideTanStackQuery,
88 * withDevtools
89 * QueryClient,
90 * } from '@tanstack/angular-query-experimental'
91 *
92 * bootstrapApplication(AppComponent,
93 * {
94 * providers: [
95 * provideTanStackQuery(new QueryClient(), withDevtools())
96 * ]
97 * }
98 * )
99 * ```
100 *
101 * **Example: using an InjectionToken**
102 *
103 * ```ts
104 * export const MY_QUERY_CLIENT = new InjectionToken('', {
105 * factory: () => new QueryClient(),
106 * })
107 *
108 * // In a lazy loaded route or lazy loaded component's providers array:
109 * providers: [provideTanStackQuery(MY_QUERY_CLIENT)]
110 * ```
111 * @param queryClient - A `QueryClient` instance, or an `InjectionToken` which provides a `QueryClient`.
112 * @param features - Optional features to configure additional Query functionality.
113 * @returns A set of providers to set up TanStack Query.
114 * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
115 * @see withDevtools
116 */
117export function provideTanStackQuery(
118 queryClient: QueryClient | InjectionToken<QueryClient>,
119 ...features: Array<QueryFeatures>
120): Array<Provider> {
121 return [
122 provideQueryClient(queryClient),
123 features.map((feature) => feature.ɵproviders),
124 ]
125}
126​
127/**
128 * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
129 *
130 * Allows to configure a `QueryClient`.
131 * @param queryClient - A `QueryClient` instance.
132 * @returns A set of providers to set up TanStack Query.
133 * @public
134 * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
135 * @deprecated Use `provideTanStackQuery` instead.
136 */
137export function provideAngularQuery(queryClient: QueryClient): Array<Provider> {
138 return provideTanStackQuery(queryClient)
139}
140​
141/**
142 * Helper type to represent a Query feature.
143 */
144export interface QueryFeature<TFeatureKind extends QueryFeatureKind> {
145 ɵkind: TFeatureKind
146 ɵproviders: Array<Provider>
147}
148​
149/**
150 * Helper function to create an object that represents a Query feature.
151 * @param kind -
152 * @param providers -
153 * @returns A Query feature.
154 */
155export function queryFeature<TFeatureKind extends QueryFeatureKind>(
156 kind: TFeatureKind,
157 providers: Array<Provider>,
158): QueryFeature<TFeatureKind> {
159 return { ɵkind: kind, ɵproviders: providers }
160}
161​
162/**
163 * A type alias that represents a feature which enables developer tools.
164 * The type is used to describe the return value of the `withDevtools` function.
165 * @public
166 * @see {@link withDevtools}
167 */
168export type DeveloperToolsFeature = QueryFeature<'DeveloperTools'>
169​
170/**
171 * A type alias that represents a feature which enables persistence.
172 * The type is used to describe the return value of the `withPersistQueryClient` function.
173 * @public
174 */
175export type PersistQueryClientFeature = QueryFeature<'PersistQueryClient'>
176​
177/**
178 * Options for configuring the TanStack Query devtools.
179 * @public
180 */
181export interface DevtoolsOptions {
182 /**
183 * Set this true if you want the devtools to default to being open
184 */
185 initialIsOpen?: boolean
186 /**
187 * The position of the TanStack logo to open and close the devtools panel.
188 * `top-left` | `top-right` | `bottom-left` | `bottom-right` | `relative`
189 * Defaults to `bottom-right`.
190 */
191 buttonPosition?: DevtoolsButtonPosition
192 /**
193 * The position of the TanStack Query devtools panel.
194 * `top` | `bottom` | `left` | `right`
195 * Defaults to `bottom`.
196 */
197 position?: DevtoolsPosition
198 /**
199 * Custom instance of QueryClient
200 */
201 client?: QueryClient
202 /**
203 * Use this so you can define custom errors that can be shown in the devtools.
204 */
205 errorTypes?: Array<DevtoolsErrorType>
206 /**
207 * Use this to pass a nonce to the style tag that is added to the document head. This is useful if you are using a Content Security Policy (CSP) nonce to allow inline styles.
208 */
209 styleNonce?: string
210 /**
211 * Use this so you can attach the devtool's styles to a specific element in the DOM.
212 */
213 shadowDOMTarget?: ShadowRoot
214 /**
215 * Set this to true to hide disabled queries from the devtools panel.
216 */
217 hideDisabledQueries?: boolean
218​
219 /**
220 * Whether the developer tools should load.
221 * - `auto`- (Default) Lazily loads devtools when in development mode. Skips loading in production mode.
222 * - `true`- Always load the devtools, regardless of the environment.
223 * - `false`- Never load the devtools, regardless of the environment.
224 *
225 * You can use `true` and `false` to override loading developer tools from an environment file.
226 * For example, a test environment might run in production mode but you may want to load developer tools.
227 *
228 * Additionally, you can use a signal in the callback to dynamically load the devtools based on a condition. For example,
229 * a signal created from a RxJS observable that listens for a keyboard shortcut.
230 *
231 * **Example**
232 * ```ts
233 * withDevtools(() => ({
234 * initialIsOpen: true,
235 * loadDevtools: inject(ExampleService).loadDevtools()
236 * }))
237 * ```
238 */
239 loadDevtools?: 'auto' | boolean
240}
241​
242/**
243 * Enables developer tools.
244 *
245 * **Example**
246 *
247 * ```ts
248 * export const appConfig: ApplicationConfig = {
249 * providers: [
250 * provideTanStackQuery(new QueryClient(), withDevtools())
251 * ]
252 * }
253 * ```
254 * By default the devtools will be loaded when Angular runs in development mode and rendered in `<body>`.
255 *
256 * If you need more control over when devtools are loaded, you can use the `loadDevtools` option. This is particularly useful if you want to load devtools based on environment configurations. For instance, you might have a test environment running in production mode but still require devtools to be available.
257 *
258 * If you need more control over where devtools are rendered, consider `injectDevtoolsPanel`. This allows rendering devtools inside your own devtools for example.
259 * @param withDevtoolsFn - A function that returns `DevtoolsOptions`.
260 * @returns A set of providers for use with `provideTanStackQuery`.
261 * @public
262 * @see {@link provideTanStackQuery}
263 * @see {@link DevtoolsOptions}
264 */
265export function withDevtools(
266 withDevtoolsFn?: () => DevtoolsOptions,
267): DeveloperToolsFeature {
268 let providers: Array<Provider> = []
269 if (!isDevMode() && !withDevtoolsFn) {
270 providers = []
271 } else {
272 providers = [
273 {
274 // Do not use provideEnvironmentInitializer while Angular < v19 is supported
275 provide: ENVIRONMENT_INITIALIZER,
276 multi: true,
277 useFactory: () => {
278 if (!isPlatformBrowser(inject(PLATFORM_ID))) return noop
279 const injectedClient = inject(QueryClient, {
280 optional: true,
281 })
282 const destroyRef = inject(DestroyRef)
283​
284 const options = computed(() => withDevtoolsFn?.() ?? {})
285​
286 let devtools: TanstackQueryDevtools | null = null
287 let el: HTMLElement | null = null
288​
289 const shouldLoadToolsSignal = computed(() => {
290 const { loadDevtools } = options()
291 return typeof loadDevtools === 'boolean'
292 ? loadDevtools
293 : isDevMode()
294 })
295​
296 const getResolvedQueryClient = () => {
297 const client = options().client ?? injectedClient
298 if (!client) {
299 throw new Error('No QueryClient found')
300 }
301 return client
302 }
303​
304 const destroyDevtools = () => {
305 devtools?.unmount()
306 el?.remove()
307 devtools = null
308 }
309​
310 return () =>
311 effect(() => {
312 const shouldLoadTools = shouldLoadToolsSignal()
313 const {
314 client,
315 position,
316 errorTypes,
317 buttonPosition,
318 initialIsOpen,
319 } = options()
320​
321 if (devtools && !shouldLoadTools) {
322 destroyDevtools()
323 return
324 } else if (devtools && shouldLoadTools) {
325 client && devtools.setClient(client)
326 position && devtools.setPosition(position)
327 errorTypes && devtools.setErrorTypes(errorTypes)
328 buttonPosition && devtools.setButtonPosition(buttonPosition)
329 initialIsOpen && devtools.setInitialIsOpen(initialIsOpen)
330 return
331 } else if (!shouldLoadTools) {
332 return
333 }
334​
335 el = document.body.appendChild(document.createElement('div'))
336 el.classList.add('tsqd-parent-container')
337​
338 import('@tanstack/query-devtools').then((queryDevtools) => {
339 devtools = new queryDevtools.TanstackQueryDevtools({
340 ...options(),
341 client: getResolvedQueryClient(),
342 queryFlavor: 'Angular Query',
343 version: '5',
344 onlineManager,
345 })
346​
347 el && devtools.mount(el)
348​
349 // Unmount the devtools on application destroy
350 destroyRef.onDestroy(destroyDevtools)
351 })
352 })
353 },
354 },
355 ]
356 }
357 return queryFeature('DeveloperTools', providers)
358}
359​
360/**
361 * A type alias that represents all Query features available for use with `provideTanStackQuery`.
362 * Features can be enabled by adding special functions to the `provideTanStackQuery` call.
363 * See documentation for each symbol to find corresponding function name. See also `provideTanStackQuery`
364 * documentation on how to use those functions.
365 * @public
366 * @see {@link provideTanStackQuery}
367 */
368export type QueryFeatures = DeveloperToolsFeature | PersistQueryClientFeature
369​
370export const queryFeatures = ['DeveloperTools', 'PersistQueryClient'] as const
371​
372export type QueryFeatureKind = (typeof queryFeatures)[number]