@@ -20,24 +20,28 @@ bootstrapApplication(AppComponent, {
2020### Component with query and mutation
2121
2222``` typescript
23+ import { Component , Injectable , inject } from ' @angular/core'
24+ import { HttpClient } from ' @angular/common/http'
25+ import { lastValueFrom } from ' rxjs'
26+
2327import {
2428 injectMutation ,
2529 injectQuery ,
2630 injectQueryClient
2731} from ' @tanstack/angular-query-experimental'
28- import { getTodos , postTodo } from ' ../my-api '
32+
2933
3034@Component ({
3135 standalone: true ,
3236 template: `
3337 <div>
38+ <button (click)="onAddTodo()">Add Todo</button>
39+
3440 <ul>
35- @for (todo of query().data ) {
41+ @for (todo of query.data(); track todo.title ) {
3642 <li>{{ todo.title }}</li>
3743 }
3844 </ul>
39-
40- <button (click)="onAddTodo()">Add Todo</button>
4145 </div>
4246 ` ,
4347})
@@ -46,26 +50,43 @@ export class TodosComponent {
4650
4751 query = injectQuery (() => ({
4852 queryKey: [' todos' ],
49- queryFn: getTodos
53+ queryFn : () => this . todoService . getTodos (),
5054 }))
5155
5256 mutation = injectMutation ((client ) => ({
53- mutationFn: postTodo ,
57+ mutationFn : ( todo : Todo ) => this . todoService . addTodo ( todo ) ,
5458 onSuccess : () => {
5559 // Invalidate and refetch by using the client directly
5660 client .invalidateQueries ({ queryKey: [' todos' ] })
5761
5862 // OR use the queryClient that is injected into the component
59- this .queryClient .invalidateQueries ({ queryKey: [' todos' ] })
63+ // this.queryClient.invalidateQueries({ queryKey: ['todos'] })
6064 }
6165 }))
6266
6367 onAddTodo() {
6468 this .mutation ().mutate ({
65- id: Date .now (),
69+ id: Date .now (). toString () ,
6670 title: ' Do Laundry' ,
6771 })
6872 }
73+
74+ @Injectable ({providedIn: ' root' })
75+ export class TodoService {
76+ private http = inject (HttpClient );
77+
78+ getTodos(): Promise <Todo []> {
79+ return lastValueFrom (this .http .get <Todo []>(' https://jsonplaceholder.typicode.com/todos' ))
80+ }
81+
82+ addTodo(todo : Todo ): Promise <Todo > {
83+ return lastValueFrom (this .http .post <Todo >(' https://jsonplaceholder.typicode.com/todos' , todo ))
84+ }
85+ }
86+
87+ interface Todo {
88+ id : string ;
89+ title : string ;
6990}
7091` ` `
7192
0 commit comments