CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tanstack--angular-query-experimental

Signals for managing, caching and syncing asynchronous and remote data in Angular

Pending
Overview
Eval results
Files

provider-setup.mddocs/

Provider Setup

Provider functions for setting up TanStack Query in Angular applications with optional features like developer tools and query client configuration.

Capabilities

Provide TanStack Query

Sets up all necessary providers to enable TanStack Query functionality in Angular applications.

/**
 * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
 * Allows to configure a QueryClient and optional features such as developer tools.
 * @param queryClient - A QueryClient instance, or an InjectionToken which provides a QueryClient
 * @param features - Optional features to configure additional Query functionality
 * @returns A set of providers to set up TanStack Query
 */
function provideTanStackQuery(
  queryClient: QueryClient | InjectionToken<QueryClient>,
  ...features: Array<QueryFeatures>
): Array<Provider>;

Usage Examples:

// Basic setup with standalone application
import { provideTanStackQuery, QueryClient } from "@tanstack/angular-query-experimental";

bootstrapApplication(AppComponent, {
  providers: [provideTanStackQuery(new QueryClient())],
});

// With developer tools
import { provideTanStackQuery, QueryClient, withDevtools } from "@tanstack/angular-query-experimental";

bootstrapApplication(AppComponent, {
  providers: [
    provideTanStackQuery(
      new QueryClient(), 
      withDevtools()
    )
  ],
});

// NgModule-based setup
import { provideTanStackQuery, QueryClient } from "@tanstack/angular-query-experimental";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [provideTanStackQuery(new QueryClient())],
  bootstrap: [AppComponent],
})
export class AppModule {}

// Using custom QueryClient configuration
import { provideTanStackQuery, QueryClient } from "@tanstack/angular-query-experimental";

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      retry: 1,
    },
    mutations: {
      retry: 1,
    },
  },
});

bootstrapApplication(AppComponent, {
  providers: [provideTanStackQuery(queryClient)],
});

Provide Query Client

Provides a QueryClient instance for dependency injection, used internally by provideTanStackQuery.

/**
 * Usually provideTanStackQuery is used once to set up TanStack Query and the QueryClient 
 * for the entire application. Internally it calls provideQueryClient.
 * You can use provideQueryClient to provide a different QueryClient instance for a part
 * of the application or for unit testing purposes.
 * @param queryClient - A QueryClient instance, or an InjectionToken which provides a QueryClient
 * @returns a provider object that can be used to provide the QueryClient instance
 */
function provideQueryClient(
  queryClient: QueryClient | InjectionToken<QueryClient>
): Provider;

Usage Examples:

// Using with InjectionToken for lazy loading
export const MY_QUERY_CLIENT = new InjectionToken('MyQueryClient', {
  factory: () => new QueryClient({
    defaultOptions: {
      queries: { staleTime: 60000 }
    }
  }),
});

// In a lazy loaded route or component's providers array:
@Component({
  providers: [provideQueryClient(MY_QUERY_CLIENT)]
})
export class LazyComponent {}

// For testing with custom QueryClient
TestBed.configureTestingModule({
  providers: [
    provideQueryClient(new QueryClient({
      defaultOptions: {
        queries: { retry: false },
        mutations: { retry: false }
      }
    }))
  ]
});

With Developer Tools

Enables developer tools feature for debugging and monitoring queries.

/**
 * Enables developer tools.
 * By default the devtools will be loaded when Angular runs in development mode.
 * @param withDevtoolsFn - A function that returns DevtoolsOptions
 * @returns A set of providers for use with provideTanStackQuery
 */
function withDevtools(
  withDevtoolsFn?: () => DevtoolsOptions
): DeveloperToolsFeature;

interface DevtoolsOptions {
  /** Set this true if you want the devtools to default to being open */
  initialIsOpen?: boolean;
  /** The position of the TanStack logo to open and close the devtools panel */
  buttonPosition?: DevtoolsButtonPosition;
  /** The position of the TanStack Query devtools panel */
  position?: DevtoolsPosition;
  /** Custom instance of QueryClient */
  client?: QueryClient;
  /** Use this so you can define custom errors that can be shown in the devtools */
  errorTypes?: Array<DevtoolsErrorType>;
  /** Use this to pass a nonce to the style tag that is added to the document head */
  styleNonce?: string;
  /** Use this so you can attach the devtool's styles to a specific element in the DOM */
  shadowDOMTarget?: ShadowRoot;
  /** Set this to true to hide disabled queries from the devtools panel */
  hideDisabledQueries?: boolean;
  /** Whether the developer tools should load */
  loadDevtools?: 'auto' | boolean;
}

type DevtoolsButtonPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'relative';
type DevtoolsPosition = 'top' | 'bottom' | 'left' | 'right';

Usage Examples:

// Basic devtools setup
export const appConfig: ApplicationConfig = {
  providers: [
    provideTanStackQuery(new QueryClient(), withDevtools())
  ]
};

// Customized devtools
export const appConfig: ApplicationConfig = {
  providers: [
    provideTanStackQuery(
      new QueryClient(), 
      withDevtools(() => ({
        initialIsOpen: true,
        position: 'bottom',
        buttonPosition: 'bottom-right'
      }))
    )
  ]
};

// Conditional loading based on environment
export const appConfig: ApplicationConfig = {
  providers: [
    provideTanStackQuery(
      new QueryClient(), 
      withDevtools(() => ({
        loadDevtools: environment.production ? false : 'auto'
      }))
    )
  ]
};

// Dynamic loading with signal
export const appConfig: ApplicationConfig = {
  providers: [
    provideTanStackQuery(
      new QueryClient(), 
      withDevtools(() => ({
        loadDevtools: inject(FeatureToggleService).showDevtools()
      }))
    )
  ]
};

Query Feature System

Helper functions for creating and managing query features.

/**
 * Helper function to create an object that represents a Query feature.
 * @param kind - The feature kind identifier
 * @param providers - Array of providers for the feature
 * @returns A Query feature object
 */
function queryFeature<TFeatureKind extends QueryFeatureKind>(
  kind: TFeatureKind,
  providers: Array<Provider>
): QueryFeature<TFeatureKind>;

interface QueryFeature<TFeatureKind extends QueryFeatureKind> {
  ɵkind: TFeatureKind;
  ɵproviders: Array<Provider>;
}

type QueryFeatureKind = 'DeveloperTools' | 'PersistQueryClient';

const queryFeatures: readonly QueryFeatureKind[] = ['DeveloperTools', 'PersistQueryClient'];

Feature Types

Type definitions for different query features.

/**
 * A type alias that represents a feature which enables developer tools.
 * The type is used to describe the return value of the withDevtools function.
 */
type DeveloperToolsFeature = QueryFeature<'DeveloperTools'>;

/**
 * A type alias that represents a feature which enables persistence.
 * The type is used to describe the return value of the withPersistQueryClient function.
 */
type PersistQueryClientFeature = QueryFeature<'PersistQueryClient'>;

/**
 * A type alias that represents all Query features available for use with provideTanStackQuery.
 * Features can be enabled by adding special functions to the provideTanStackQuery call.
 */
type QueryFeatures = DeveloperToolsFeature | PersistQueryClientFeature;

Provide Is Restoring

Provider for isRestoring signal used by TanStack Query persist client plugins.

/**
 * Used by TanStack Query Angular persist client plugin to provide the signal that tracks the restore state
 * @param isRestoring - a readonly signal that returns a boolean
 * @returns Provider for the isRestoring signal
 */
function provideIsRestoring(isRestoring: Signal<boolean>): Provider;

Usage Examples:

// For use with persistence plugins
import { provideIsRestoring } from "@tanstack/angular-query-experimental";
import { signal } from "@angular/core";

const isRestoringSignal = signal(false);

export const appConfig: ApplicationConfig = {
  providers: [
    provideTanStackQuery(new QueryClient()),
    provideIsRestoring(isRestoringSignal.asReadonly())
  ]
};

Deprecated Functions

Legacy functions maintained for backward compatibility.

/**
 * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
 * @param queryClient - A QueryClient instance
 * @returns A set of providers to set up TanStack Query
 * @deprecated Use provideTanStackQuery instead
 */
function provideAngularQuery(queryClient: QueryClient): Array<Provider>;

Advanced Configuration Patterns

Environment-Specific Setup

// app.config.ts
import { ApplicationConfig, isDevMode } from '@angular/core';
import { provideTanStackQuery, QueryClient, withDevtools } from '@tanstack/angular-query-experimental';

export const appConfig: ApplicationConfig = {
  providers: [
    provideTanStackQuery(
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: isDevMode() ? 0 : 5 * 60 * 1000, // No cache in dev, 5min in prod
            retry: isDevMode() ? false : 1, // No retry in dev
          }
        }
      }),
      ...(isDevMode() ? [withDevtools()] : [])
    )
  ]
};

Feature-Based Setup

// query.config.ts
export function createQueryConfig(features: { devtools?: boolean; persistence?: boolean } = {}) {
  const queryFeatures: QueryFeatures[] = [];
  
  if (features.devtools) {
    queryFeatures.push(withDevtools(() => ({
      initialIsOpen: false,
      position: 'bottom'
    })));
  }
  
  // If persistence feature existed, it would be added here
  // if (features.persistence) {
  //   queryFeatures.push(withPersistQueryClient(...));
  // }
  
  return provideTanStackQuery(
    new QueryClient({
      defaultOptions: {
        queries: {
          staleTime: 5 * 60 * 1000,
          retry: 1
        }
      }
    }),
    ...queryFeatures
  );
}

// app.config.ts
export const appConfig: ApplicationConfig = {
  providers: [
    createQueryConfig({ devtools: !environment.production })
  ]
};

Lazy Loading with Custom QueryClient

// feature.routes.ts
export const routes: Routes = [
  {
    path: 'feature',
    loadComponent: () => import('./feature.component').then(m => m.FeatureComponent),
    providers: [
      // Custom QueryClient for this feature
      {
        provide: FEATURE_QUERY_CLIENT,
        useFactory: () => new QueryClient({
          defaultOptions: {
            queries: {
              staleTime: 10 * 60 * 1000 // 10 minutes for this feature
            }
          }
        })
      },
      provideQueryClient(FEATURE_QUERY_CLIENT)
    ]
  }
];

export const FEATURE_QUERY_CLIENT = new InjectionToken<QueryClient>('FeatureQueryClient');

Testing Configuration

// test-utils.ts
export function setupTestingModule(options: { 
  queryClient?: QueryClient;
  mockQueries?: boolean;
} = {}) {
  const queryClient = options.queryClient || new QueryClient({
    defaultOptions: {
      queries: { retry: false },
      mutations: { retry: false }
    },
    logger: {
      log: console.log,
      warn: console.warn,
      error: () => {}, // Silence errors in tests
    },
  });

  return TestBed.configureTestingModule({
    providers: [
      provideTanStackQuery(queryClient)
    ]
  });
}

Install with Tessl CLI

npx tessl i tessl/npm-tanstack--angular-query-experimental

docs

index.md

infinite-queries.md

multi-query-operations.md

mutation-management.md

options-helpers.md

provider-setup.md

query-management.md

status-monitoring.md

tile.json