Query Docs
Guides & Concepts
- Important Defaults
- Queries
- Query Keys
- Query Functions
- Query Options
- Network Mode
- Parallel Queries
- Dependent Queries
- Background Fetching Indicators
- Window Focus Refetching
- Disabling/Pausing Queries
- Query Retries
- Paginated Queries
- Infinite Queries
- Initial Query Data
- Placeholder Query Data
- Mutations
- Mutation Options
- Query Invalidation
- Invalidation from Mutations
- Optimistic Updates
- Query Cancellation
- Scroll Restoration
- Filters
- Caching
- Default Query Fn
- Testing
- Does this replace state managers?
AI/LLM: This documentation page is available in plain markdown format at/query/latest/docs/framework/angular/guides/query-options.md
Guides & Concepts
Query Options
One of the best ways to share queryKey and queryFn between multiple places, yet keep them co-located to one another, is to use the queryOptions helper. At runtime, this helper just returns whatever you pass into it, but it has a lot of advantages when using it with TypeScript. You can define all possible options for a query in one place, and you'll also get type inference and type safety for all of them.
ts
import { queryOptions, noop } from '@tanstack/angular-query-experimental'
@Injectable({
providedIn: 'root',
})
export class QueriesService {
private readonly http = inject(HttpClient)
post(postId: number) {
return queryOptions({
queryKey: ['post', postId],
queryFn: () => {
return lastValueFrom(
this.http.get<Post>(
`https://jsonplaceholder.typicode.com/posts/${postId}`,
),
)
},
})
}
}
// usage:
postId = input.required({
transform: numberAttribute,
})
queries = inject(QueriesService)
postQuery = injectQuery(() => this.queries.post(this.postId()))
queryClient.query(this.queries.post(23)).catch(noop)
queryClient.setQueryData(this.queries.post(42).queryKey, newPost)For Infinite Queries, a separate infiniteQueryOptions helper is available.
You can still override some options at the component level. A very common and useful pattern is to create per-component select functions:
ts
// Type inference still works, so groupQuery.data will be the return type of select instead of queryFn
queries = inject(QueriesService)
groupQuery = injectQuery(() => ({
...groupOptions(1),
select: (data) => data.title,
}))