Open History to see the last commit
1---
2id: quick-start
3title: Quick Start
4---
5β
6[//]: # 'Example'
7β
8If you're looking for a fully functioning example, please have a look at our [basic codesandbox example](./examples/basic)
9β
10### Configure the QueryClient
11β
12Pass a factory to `provideTanStackQuery`. Angular runs it once per injector and in an injection context, so it can use `inject()`.
13β
14```ts
15import { provideHttpClient } from '@angular/common/http'
16import { bootstrapApplication } from '@angular/platform-browser'
17import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'
18β
19bootstrapApplication(AppComponent, {
20 providers: [
21 provideHttpClient(),
22 provideTanStackQuery(() => new QueryClient()),
23 ],
24})
25```
26β
27### Component with query and mutation
28β
29```angular-ts
30import { HttpClient } from '@angular/common/http'
31import { Component, Injectable, inject } from '@angular/core'
32import {
33 injectMutation,
34 injectQuery,
35 QueryClient,
36} from '@tanstack/angular-query'
37import { lastValueFrom } from 'rxjs'
38β
39@Component({
40 template: `
41 <div>
42 <button (click)="onAddTodo()">Add Todo</button>
43β
44 <ul>
45 @for (todo of todosQuery.data(); track todo.title) {
46 <li>{{ todo.title }}</li>
47 }
48 </ul>
49 </div>
50 `,
51})
52export class TodosComponent {
53 readonly todoService = inject(TodoService)
54 readonly queryClient = inject(QueryClient)
55β
56 readonly todosQuery = injectQuery(() => ({
57 queryKey: ['todos'],
58 queryFn: () => this.todoService.getTodos(),
59 }))
60β
61 readonly addTodoMutation = injectMutation(() => ({
62 mutationFn: (todo: Todo) => this.todoService.addTodo(todo),
63 onSuccess: () => {
64 this.queryClient.invalidateQueries({ queryKey: ['todos'] })
65 },
66 }))
67β
68 onAddTodo() {
69 this.addTodoMutation.mutate({
70 id: Date.now().toString(),
71 title: 'Do Laundry',
72 })
73 }
74}
75β
76@Injectable({ providedIn: 'root' })
77export class TodoService {
78 private readonly http = inject(HttpClient)
79β
80 getTodos(): Promise<Todo[]> {
81 return lastValueFrom(
82 this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos'),
83 )
84 }
85β
86 addTodo(todo: Todo): Promise<Todo> {
87 return lastValueFrom(
88 this.http.post<Todo>('https://jsonplaceholder.typicode.com/todos', todo),
89 )
90 }
91}
92β
93interface Todo {
94 id: string
95 title: string
96}
97```
98β
99[//]: # 'Example'