0
# Provider Setup
1
2
Provider functions for setting up TanStack Query in Angular applications with optional features like developer tools and query client configuration.
3
4
## Capabilities
5
6
### Provide TanStack Query
7
8
Sets up all necessary providers to enable TanStack Query functionality in Angular applications.
9
10
```typescript { .api }
11
/**
12
* Sets up providers necessary to enable TanStack Query functionality for Angular applications.
13
* Allows to configure a QueryClient and optional features such as developer tools.
14
* @param queryClient - A QueryClient instance, or an InjectionToken which provides a QueryClient
15
* @param features - Optional features to configure additional Query functionality
16
* @returns A set of providers to set up TanStack Query
17
*/
18
function provideTanStackQuery(
19
queryClient: QueryClient | InjectionToken<QueryClient>,
20
...features: Array<QueryFeatures>
21
): Array<Provider>;
22
```
23
24
**Usage Examples:**
25
26
```typescript
27
// Basic setup with standalone application
28
import { provideTanStackQuery, QueryClient } from "@tanstack/angular-query-experimental";
29
30
bootstrapApplication(AppComponent, {
31
providers: [provideTanStackQuery(new QueryClient())],
32
});
33
34
// With developer tools
35
import { provideTanStackQuery, QueryClient, withDevtools } from "@tanstack/angular-query-experimental";
36
37
bootstrapApplication(AppComponent, {
38
providers: [
39
provideTanStackQuery(
40
new QueryClient(),
41
withDevtools()
42
)
43
],
44
});
45
46
// NgModule-based setup
47
import { provideTanStackQuery, QueryClient } from "@tanstack/angular-query-experimental";
48
49
@NgModule({
50
declarations: [AppComponent],
51
imports: [BrowserModule],
52
providers: [provideTanStackQuery(new QueryClient())],
53
bootstrap: [AppComponent],
54
})
55
export class AppModule {}
56
57
// Using custom QueryClient configuration
58
import { provideTanStackQuery, QueryClient } from "@tanstack/angular-query-experimental";
59
60
const queryClient = new QueryClient({
61
defaultOptions: {
62
queries: {
63
staleTime: 5 * 60 * 1000, // 5 minutes
64
retry: 1,
65
},
66
mutations: {
67
retry: 1,
68
},
69
},
70
});
71
72
bootstrapApplication(AppComponent, {
73
providers: [provideTanStackQuery(queryClient)],
74
});
75
```
76
77
### Provide Query Client
78
79
Provides a QueryClient instance for dependency injection, used internally by provideTanStackQuery.
80
81
```typescript { .api }
82
/**
83
* Usually provideTanStackQuery is used once to set up TanStack Query and the QueryClient
84
* for the entire application. Internally it calls provideQueryClient.
85
* You can use provideQueryClient to provide a different QueryClient instance for a part
86
* of the application or for unit testing purposes.
87
* @param queryClient - A QueryClient instance, or an InjectionToken which provides a QueryClient
88
* @returns a provider object that can be used to provide the QueryClient instance
89
*/
90
function provideQueryClient(
91
queryClient: QueryClient | InjectionToken<QueryClient>
92
): Provider;
93
```
94
95
**Usage Examples:**
96
97
```typescript
98
// Using with InjectionToken for lazy loading
99
export const MY_QUERY_CLIENT = new InjectionToken('MyQueryClient', {
100
factory: () => new QueryClient({
101
defaultOptions: {
102
queries: { staleTime: 60000 }
103
}
104
}),
105
});
106
107
// In a lazy loaded route or component's providers array:
108
@Component({
109
providers: [provideQueryClient(MY_QUERY_CLIENT)]
110
})
111
export class LazyComponent {}
112
113
// For testing with custom QueryClient
114
TestBed.configureTestingModule({
115
providers: [
116
provideQueryClient(new QueryClient({
117
defaultOptions: {
118
queries: { retry: false },
119
mutations: { retry: false }
120
}
121
}))
122
]
123
});
124
```
125
126
### With Developer Tools
127
128
Enables developer tools feature for debugging and monitoring queries.
129
130
```typescript { .api }
131
/**
132
* Enables developer tools.
133
* By default the devtools will be loaded when Angular runs in development mode.
134
* @param withDevtoolsFn - A function that returns DevtoolsOptions
135
* @returns A set of providers for use with provideTanStackQuery
136
*/
137
function withDevtools(
138
withDevtoolsFn?: () => DevtoolsOptions
139
): DeveloperToolsFeature;
140
141
interface DevtoolsOptions {
142
/** Set this true if you want the devtools to default to being open */
143
initialIsOpen?: boolean;
144
/** The position of the TanStack logo to open and close the devtools panel */
145
buttonPosition?: DevtoolsButtonPosition;
146
/** The position of the TanStack Query devtools panel */
147
position?: DevtoolsPosition;
148
/** Custom instance of QueryClient */
149
client?: QueryClient;
150
/** Use this so you can define custom errors that can be shown in the devtools */
151
errorTypes?: Array<DevtoolsErrorType>;
152
/** Use this to pass a nonce to the style tag that is added to the document head */
153
styleNonce?: string;
154
/** Use this so you can attach the devtool's styles to a specific element in the DOM */
155
shadowDOMTarget?: ShadowRoot;
156
/** Set this to true to hide disabled queries from the devtools panel */
157
hideDisabledQueries?: boolean;
158
/** Whether the developer tools should load */
159
loadDevtools?: 'auto' | boolean;
160
}
161
162
type DevtoolsButtonPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'relative';
163
type DevtoolsPosition = 'top' | 'bottom' | 'left' | 'right';
164
```
165
166
**Usage Examples:**
167
168
```typescript
169
// Basic devtools setup
170
export const appConfig: ApplicationConfig = {
171
providers: [
172
provideTanStackQuery(new QueryClient(), withDevtools())
173
]
174
};
175
176
// Customized devtools
177
export const appConfig: ApplicationConfig = {
178
providers: [
179
provideTanStackQuery(
180
new QueryClient(),
181
withDevtools(() => ({
182
initialIsOpen: true,
183
position: 'bottom',
184
buttonPosition: 'bottom-right'
185
}))
186
)
187
]
188
};
189
190
// Conditional loading based on environment
191
export const appConfig: ApplicationConfig = {
192
providers: [
193
provideTanStackQuery(
194
new QueryClient(),
195
withDevtools(() => ({
196
loadDevtools: environment.production ? false : 'auto'
197
}))
198
)
199
]
200
};
201
202
// Dynamic loading with signal
203
export const appConfig: ApplicationConfig = {
204
providers: [
205
provideTanStackQuery(
206
new QueryClient(),
207
withDevtools(() => ({
208
loadDevtools: inject(FeatureToggleService).showDevtools()
209
}))
210
)
211
]
212
};
213
```
214
215
### Query Feature System
216
217
Helper functions for creating and managing query features.
218
219
```typescript { .api }
220
/**
221
* Helper function to create an object that represents a Query feature.
222
* @param kind - The feature kind identifier
223
* @param providers - Array of providers for the feature
224
* @returns A Query feature object
225
*/
226
function queryFeature<TFeatureKind extends QueryFeatureKind>(
227
kind: TFeatureKind,
228
providers: Array<Provider>
229
): QueryFeature<TFeatureKind>;
230
231
interface QueryFeature<TFeatureKind extends QueryFeatureKind> {
232
ɵkind: TFeatureKind;
233
ɵproviders: Array<Provider>;
234
}
235
236
type QueryFeatureKind = 'DeveloperTools' | 'PersistQueryClient';
237
238
const queryFeatures: readonly QueryFeatureKind[] = ['DeveloperTools', 'PersistQueryClient'];
239
```
240
241
### Feature Types
242
243
Type definitions for different query features.
244
245
```typescript { .api }
246
/**
247
* A type alias that represents a feature which enables developer tools.
248
* The type is used to describe the return value of the withDevtools function.
249
*/
250
type DeveloperToolsFeature = QueryFeature<'DeveloperTools'>;
251
252
/**
253
* A type alias that represents a feature which enables persistence.
254
* The type is used to describe the return value of the withPersistQueryClient function.
255
*/
256
type PersistQueryClientFeature = QueryFeature<'PersistQueryClient'>;
257
258
/**
259
* A type alias that represents all Query features available for use with provideTanStackQuery.
260
* Features can be enabled by adding special functions to the provideTanStackQuery call.
261
*/
262
type QueryFeatures = DeveloperToolsFeature | PersistQueryClientFeature;
263
```
264
265
### Provide Is Restoring
266
267
Provider for isRestoring signal used by TanStack Query persist client plugins.
268
269
```typescript { .api }
270
/**
271
* Used by TanStack Query Angular persist client plugin to provide the signal that tracks the restore state
272
* @param isRestoring - a readonly signal that returns a boolean
273
* @returns Provider for the isRestoring signal
274
*/
275
function provideIsRestoring(isRestoring: Signal<boolean>): Provider;
276
```
277
278
**Usage Examples:**
279
280
```typescript
281
// For use with persistence plugins
282
import { provideIsRestoring } from "@tanstack/angular-query-experimental";
283
import { signal } from "@angular/core";
284
285
const isRestoringSignal = signal(false);
286
287
export const appConfig: ApplicationConfig = {
288
providers: [
289
provideTanStackQuery(new QueryClient()),
290
provideIsRestoring(isRestoringSignal.asReadonly())
291
]
292
};
293
```
294
295
### Deprecated Functions
296
297
Legacy functions maintained for backward compatibility.
298
299
```typescript { .api }
300
/**
301
* Sets up providers necessary to enable TanStack Query functionality for Angular applications.
302
* @param queryClient - A QueryClient instance
303
* @returns A set of providers to set up TanStack Query
304
* @deprecated Use provideTanStackQuery instead
305
*/
306
function provideAngularQuery(queryClient: QueryClient): Array<Provider>;
307
```
308
309
## Advanced Configuration Patterns
310
311
### Environment-Specific Setup
312
313
```typescript
314
// app.config.ts
315
import { ApplicationConfig, isDevMode } from '@angular/core';
316
import { provideTanStackQuery, QueryClient, withDevtools } from '@tanstack/angular-query-experimental';
317
318
export const appConfig: ApplicationConfig = {
319
providers: [
320
provideTanStackQuery(
321
new QueryClient({
322
defaultOptions: {
323
queries: {
324
staleTime: isDevMode() ? 0 : 5 * 60 * 1000, // No cache in dev, 5min in prod
325
retry: isDevMode() ? false : 1, // No retry in dev
326
}
327
}
328
}),
329
...(isDevMode() ? [withDevtools()] : [])
330
)
331
]
332
};
333
```
334
335
### Feature-Based Setup
336
337
```typescript
338
// query.config.ts
339
export function createQueryConfig(features: { devtools?: boolean; persistence?: boolean } = {}) {
340
const queryFeatures: QueryFeatures[] = [];
341
342
if (features.devtools) {
343
queryFeatures.push(withDevtools(() => ({
344
initialIsOpen: false,
345
position: 'bottom'
346
})));
347
}
348
349
// If persistence feature existed, it would be added here
350
// if (features.persistence) {
351
// queryFeatures.push(withPersistQueryClient(...));
352
// }
353
354
return provideTanStackQuery(
355
new QueryClient({
356
defaultOptions: {
357
queries: {
358
staleTime: 5 * 60 * 1000,
359
retry: 1
360
}
361
}
362
}),
363
...queryFeatures
364
);
365
}
366
367
// app.config.ts
368
export const appConfig: ApplicationConfig = {
369
providers: [
370
createQueryConfig({ devtools: !environment.production })
371
]
372
};
373
```
374
375
### Lazy Loading with Custom QueryClient
376
377
```typescript
378
// feature.routes.ts
379
export const routes: Routes = [
380
{
381
path: 'feature',
382
loadComponent: () => import('./feature.component').then(m => m.FeatureComponent),
383
providers: [
384
// Custom QueryClient for this feature
385
{
386
provide: FEATURE_QUERY_CLIENT,
387
useFactory: () => new QueryClient({
388
defaultOptions: {
389
queries: {
390
staleTime: 10 * 60 * 1000 // 10 minutes for this feature
391
}
392
}
393
})
394
},
395
provideQueryClient(FEATURE_QUERY_CLIENT)
396
]
397
}
398
];
399
400
export const FEATURE_QUERY_CLIENT = new InjectionToken<QueryClient>('FeatureQueryClient');
401
```
402
403
### Testing Configuration
404
405
```typescript
406
// test-utils.ts
407
export function setupTestingModule(options: {
408
queryClient?: QueryClient;
409
mockQueries?: boolean;
410
} = {}) {
411
const queryClient = options.queryClient || new QueryClient({
412
defaultOptions: {
413
queries: { retry: false },
414
mutations: { retry: false }
415
},
416
logger: {
417
log: console.log,
418
warn: console.warn,
419
error: () => {}, // Silence errors in tests
420
},
421
});
422
423
return TestBed.configureTestingModule({
424
providers: [
425
provideTanStackQuery(queryClient)
426
]
427
});
428
}
429
```