Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .changeset/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
"$schema": "https://unpkg.com/@changesets/config@3.1.2/schema.json",
"changelog": [
"@svitejs/changesets-changelog-github-compact",
{ "repo": "TanStack/query" }
{
"repo": "TanStack/query"
}
],
"commit": false,
"access": "public",
Expand All @@ -11,6 +13,7 @@
"fixed": [
[
"@tanstack/angular-query-experimental",
"@tanstack/angular-query-devtools",
"@tanstack/angular-query-persist-client",
"@tanstack/eslint-plugin-query",
"@tanstack/preact-query",
Expand Down Expand Up @@ -43,4 +46,4 @@
"___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH": {
"onlyUpdatePeerDependentsWhenOutOfRange": true
}
}
}
5 changes: 5 additions & 0 deletions .changeset/deep-crews-open.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/angular-query-experimental': minor
---

require Angular v19+ and use Angular component effect scheduling
8 changes: 8 additions & 0 deletions docs/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@
"label": "Devtools",
"to": "framework/angular/devtools"
},
{
"label": "SSR",
"to": "framework/angular/guides/ssr"
},
{
"label": "TypeScript",
"to": "framework/angular/typescript"
Expand Down Expand Up @@ -1546,6 +1550,10 @@
{
"label": "Devtools embedded panel",
"to": "framework/angular/examples/devtools-panel"
},
{
"label": "SSR",
"to": "framework/angular/examples/ssr"
}
]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Because TanStack Query's fetching mechanisms are agnostically built on Promises,
- Mock responses in unit tests using [provideHttpClientTesting](https://angular.dev/guide/http/testing).
- [Interceptors](https://angular.dev/guide/http/interceptors) can be used for a wide range of functionality including adding authentication headers, performing logging, etc. While some data fetching libraries have their own interceptor system, `HttpClient` interceptors are integrated with Angular's dependency injection system.
- `HttpClient` automatically informs [`PendingTasks`](https://angular.dev/api/core/PendingTasks#), which enables Angular to be aware of pending requests. Unit tests and SSR can use the resulting application _stableness_ information to wait for pending requests to finish. This makes unit testing much easier for [Zoneless](https://angular.dev/guide/zoneless) applications.
- When using SSR, `HttpClient` will [cache requests](https://angular.dev/guide/ssr#caching-data-when-using-HttpClient) performed on the server. This will prevent unneeded requests on the client. `HttpClient` SSR caching works out of the box. TanStack Query has its own hydration functionality which may be more powerful but requires some setup. Which one fits your needs best depends on your use case.
- When using SSR, `HttpClient` will [cache requests](https://angular.dev/guide/ssr#caching-data-when-using-HttpClient) performed on the server. TanStack Query will additionally [hydrate its cache](./guides/ssr.md) from the server-rendered HTML when you use `provideTanStackQuery`.

### Using observables in `queryFn`

Expand All @@ -36,8 +36,6 @@ class ExampleComponent {
```

> Since Angular is moving towards RxJS as an optional dependency, it's expected that `HttpClient` will also support promises in the future.
>
> Support for observables in TanStack Query for Angular is planned.

## Comparison table

Expand Down
74 changes: 39 additions & 35 deletions docs/framework/angular/devtools.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,23 @@ title: Devtools

## Enable devtools

Add the devtools package (in addition to `@tanstack/angular-query-experimental`):

```bash
npm install @tanstack/angular-query-devtools
```

The devtools help you debug and inspect your queries and mutations. You can enable the devtools by adding `withDevtools` to `provideTanStackQuery`.

By default, Angular Query Devtools are only included in development mode bundles, so you don't need to worry about excluding them during a production build.
By default, Angular Query Devtools only load in development.

```ts
import {
QueryClient,
provideTanStackQuery,
} from '@tanstack/angular-query-experimental'

import { withDevtools } from '@tanstack/angular-query-experimental/devtools'
import { withDevtools } from '@tanstack/angular-query-devtools'

export const appConfig: ApplicationConfig = {
providers: [provideTanStackQuery(new QueryClient(), withDevtools())],
Expand All @@ -30,28 +36,28 @@ export const appConfig: ApplicationConfig = {

## Devtools in production

Devtools are automatically excluded from production builds. However, it might be desirable to lazy load the devtools in production.

To use `withDevtools` in production builds, import using the `production` sub-path. The function exported from the production subpath is identical to the main one, but won't be excluded from production builds.
If you need the real implementation in production, import from the `production` entrypoint.

```ts
import { withDevtools } from '@tanstack/angular-query-experimental/devtools/production'
import { withDevtools } from '@tanstack/angular-query-devtools/production'
```

To control when devtools are loaded, you can use the `loadDevtools` option.
To control when devtools are loaded, use the `loadDevtools` option.

When not setting the option or setting it to 'auto', the devtools will be loaded automatically only when Angular runs in development mode.
When omitted or set to `'auto'`, devtools only load in development mode.

```ts
import { withDevtools } from '@tanstack/angular-query-experimental/devtools'
import { withDevtools } from '@tanstack/angular-query-devtools'

provideTanStackQuery(new QueryClient(), withDevtools())
providers: [provideTanStackQuery(new QueryClient(), withDevtools())]

// which is equivalent to
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({ loadDevtools: 'auto' })),
)
providers: [
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({ loadDevtools: 'auto' })),
),
]
```

When setting the option to true, the devtools will be loaded in both development and production mode.
Expand All @@ -61,29 +67,30 @@ This is useful if you want to load devtools based on [Angular environment config
```ts
import { environment } from './environments/environment'
// Make sure to use the production sub-path to load devtools in production builds
import { withDevtools } from '@tanstack/angular-query-experimental/devtools/production'

provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({ loadDevtools: environment.loadDevtools })),
)
import { withDevtools } from '@tanstack/angular-query-devtools/production'

providers: [
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({ loadDevtools: environment.loadDevtools })),
),
]
```

When setting the option to false, the devtools will not be loaded.

```ts
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({ loadDevtools: false })),
)
providers: [
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({ loadDevtools: false })),
),
]
```

## Derive options through reactivity

Options are passed to `withDevtools` from a callback function to support reactivity through signals. In the following example
a signal is created from a RxJS observable that emits on a keyboard shortcut. When the derived signal is set to true, the devtools are lazily loaded.

The example below always loads devtools in development mode and loads on-demand in production mode when a keyboard shortcut is pressed.
Options can be returned from a callback so they can react to signals. For example, a signal derived from a keyboard shortcut can enable devtools on demand:

```ts
import { Injectable, isDevMode } from '@angular/core'
Expand All @@ -107,14 +114,12 @@ export class DevtoolsOptionsManager {
}
```

If you want to use an injectable such as a service in the callback you can use `deps`. The injected value will be passed as parameter to the callback function.

This is similar to `deps` in Angular's [`useFactory`](https://angular.dev/guide/di/dependency-injection-providers#factory-providers-usefactory) provider.
To use an injectable such as a service in the callback, pass it through `deps`:

```ts
// ...
// 👇 Note we import from the production sub-path to enable devtools lazy loading in production builds
import { withDevtools } from '@tanstack/angular-query-experimental/devtools/production'
import { withDevtools } from '@tanstack/angular-query-devtools/production'

export const appConfig: ApplicationConfig = {
providers: [
Expand All @@ -126,7 +131,6 @@ export const appConfig: ApplicationConfig = {
loadDevtools: devToolsOptionsManager.loadDevtools(),
}),
{
// `deps` is used to inject and pass `DevtoolsOptionsManager` to the `withDevtools` callback.
deps: [DevtoolsOptionsManager],
},
),
Expand All @@ -140,8 +144,8 @@ export const appConfig: ApplicationConfig = {
Of these options `loadDevtools`, `client`, `position`, `errorTypes`, `buttonPosition`, and `initialIsOpen` support reactivity through signals.

- `loadDevtools?: 'auto' | boolean`
- Defaults to `auto`: lazily loads devtools when in development mode. Skips loading in production mode.
- Use this to control if the devtools are loaded.
- Omit or `'auto'`: load devtools only in development mode.
- Use this to control whether devtools load when using the `/production` import.
- `initialIsOpen?: Boolean`
- Set this to `true` if you want the tools to default to being open
- `buttonPosition?: "top-left" | "top-right" | "bottom-left" | "bottom-right" | "relative"`
Expand Down
6 changes: 3 additions & 3 deletions docs/framework/angular/guides/caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ Let's assume we are using the default `gcTime` of **5 minutes** and the default
- When the request completes successfully, the cache's data under the `['todos']` key is updated with the new data, and both instances are updated with the new data.
- Both instances of the `injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos }))` query are destroyed and no longer in use.
- Since there are no more active instances of this query, a garbage collection timeout is set using `gcTime` to delete and garbage collect the query (defaults to **5 minutes**).
- Before the cache timeout has completed, another instance of `injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos }))` mounts. The query immediately returns the available cached data while the `fetchTodos` function is being run in the background. When it completes successfully, it will populate the cache with fresh data.
- The final instance of `injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos }))` gets destroyed.
- No more instances of `injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos }))` appear within **5 minutes**.
- Before the cache timeout has completed, another instance of `injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })` mounts. The query immediately returns the available cached data while the `fetchTodos` function is being run in the background. When it completes successfully, it will populate the cache with fresh data.
- The final instance of `injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })` gets destroyed.
- No more instances of `injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })` appear within **5 minutes**.
- The cached data under the `['todos']` key is deleted and garbage collected.

For more advanced use-cases, see [injectQuery](../reference/functions/injectQuery.md).
16 changes: 12 additions & 4 deletions docs/framework/angular/guides/default-query-function.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,27 @@ bootstrapApplication(MyAppComponent, {
providers: [provideTanStackQuery(queryClient)],
})

export class PostsComponent {
@Component({
// ...
})
class PostsComponent {
// All you have to do now is pass a key!
postsQuery = injectQuery<Array<Post>>(() => ({
queryKey: ['/posts'],
}))
// ...
}

export class PostComponent {
@Component({
// ...
})
class PostComponent {
postId = input(0)

// You can even leave out the queryFn and just go straight into options
postQuery = injectQuery<Post>(() => ({
enabled: this.postIdSignal() > 0,
queryKey: [`/posts/${this.postIdSignal()}`],
enabled: this.postId() > 0,
queryKey: [`/posts/${this.postId()}`],
}))
// ...
}
Expand Down
24 changes: 20 additions & 4 deletions docs/framework/angular/guides/dependent-queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ replace: { 'useQuery': 'injectQuery', 'useQueries': 'injectQueries' }
```ts
// Get the user
userQuery = injectQuery(() => ({
queryKey: ['user', email],
queryFn: getUserByEmail,
queryKey: ['user', this.email()],
queryFn: this.getUserByEmail,
}))

// Then get the user's projects
projectsQuery = injectQuery(() => ({
queryKey: ['projects', this.userQuery.data()?.id],
queryFn: getProjectsByUser,
queryFn: this.getProjectsByUser,
// The query will not execute until the user id exists
enabled: !!this.userQuery.data()?.id,
}))
Expand All @@ -26,8 +26,24 @@ projectsQuery = injectQuery(() => ({
[//]: # 'Example'
[//]: # 'Example2'

Dynamic parallel query - `injectQueries` can depend on a previous query also, here's how to achieve this:

```ts
// injectQueries is under development for Angular Query
// Get the users ids
userIdsQuery = injectQuery(() => ({
queryKey: ['users'],
queryFn: getUsersData,
select: (users) => users.map((user) => user.id),
}))

// Then get the users' messages
usersMessages = injectQueries(() => ({
queries:
this.userIdsQuery.data()?.map((id) => ({
queryKey: ['messages', id],
queryFn: () => getMessagesByUsers(id),
})) ?? [],
}))
```

[//]: # 'Example2'
6 changes: 3 additions & 3 deletions docs/framework/angular/guides/disabling-queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ replace: { 'useQuery': 'injectQuery' }
template: `<div>
<button (click)="query.refetch()">Fetch Todos</button>
@if (query.data()) {
@if (query.data(); as data) {
<ul>
@for (todo of query.data(); track todo.id) {
@for (todo of data; track todo.id) {
<li>{{ todo.title }}</li>
}
</ul>
Expand Down Expand Up @@ -70,7 +70,7 @@ export class TodosComponent {
[//]: # 'Example3'

```angular-ts
import { skipToken, injectQuery } from '@tanstack/query-angular'
import { skipToken, injectQuery } from '@tanstack/angular-query-experimental'
@Component({
selector: 'todos',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ replace:
'useQuery': 'injectQuery',
'useMutation': 'injectMutation',
'hook': 'function',
'Redux, MobX or': 'NgRx Store or',
'Redux, MobX, Zustand': 'NgRx Store, custom services with RxJS',
}
---
1 change: 0 additions & 1 deletion docs/framework/angular/guides/important-defaults.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ title: Important Defaults
ref: docs/framework/react/guides/important-defaults.md
replace:
{
'React': 'Angular',
'react-query': 'angular-query',
'useQuery': 'injectQuery',
'useInfiniteQuery': 'injectInfiniteQuery',
Expand Down
2 changes: 2 additions & 0 deletions docs/framework/angular/guides/infinite-queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ export class Example {
template: ` <list-component (endReached)="fetchNextPage()" /> `,
})
export class Example {
projectsService = inject(ProjectsService)
query = injectInfiniteQuery(() => ({
queryKey: ['projects'],
queryFn: async ({ pageParam }) => {
Expand Down
10 changes: 6 additions & 4 deletions docs/framework/angular/guides/initial-query-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ result = injectQuery(() => ({
```ts
result = injectQuery(() => ({
queryKey: ['todo', this.todoId()],
queryFn: () => fetch('/todos'),
queryFn: () => fetch(`/todos/${this.todoId()}`),
initialData: () => {
// Use a todo from the 'todos' query as the initial data for this todo query
return this.queryClient
Expand All @@ -99,9 +99,11 @@ result = injectQuery(() => ({
queryKey: ['todos', this.todoId()],
queryFn: () => fetch(`/todos/${this.todoId()}`),
initialData: () =>
queryClient.getQueryData(['todos'])?.find((d) => d.id === this.todoId()),
this.queryClient
.getQueryData(['todos'])
?.find((d) => d.id === this.todoId()),
initialDataUpdatedAt: () =>
queryClient.getQueryState(['todos'])?.dataUpdatedAt,
this.queryClient.getQueryState(['todos'])?.dataUpdatedAt,
}))
```

Expand All @@ -114,7 +116,7 @@ result = injectQuery(() => ({
queryFn: () => fetch(`/todos/${this.todoId()}`),
initialData: () => {
// Get the query state
const state = queryClient.getQueryState(['todos'])
const state = this.queryClient.getQueryState(['todos'])

// If the query exists and has data that is no older than 10 seconds...
if (state && Date.now() - state.dataUpdatedAt <= 10 * 1000) {
Expand Down
Loading