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