Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

basic-example.component.ts

165 lines4.3 KB

1import { AngularQueryDevtools } from '@tanstack/angular-query-devtools-experimental'
2import {
3 ChangeDetectionStrategy,
4 Component,
5 EventEmitter,
6 Input,
7 Output,
8 inject,
9 signal,
10} from '@angular/core'
11import {
12 injectQuery,
13 injectQueryClient,
14} from '@tanstack/angular-query-experimental'
15import { HttpClient } from '@angular/common/http'
16import { fromEvent, lastValueFrom, takeUntil } from 'rxjs'
17​
18type Post = {
19 id: number
20 title: string
21 body: string
23​
24@Component({
25 changeDetection: ChangeDetectionStrategy.OnPush,
26 selector: 'post',
27 standalone: true,
28 template: `
29 <div>
30 <div>
31 <a (click)="setPostId.emit(-1)" href="#"> Back </a>
32 </div>
33 @if (postQuery.status() === 'pending') {
34 Loading...
35 } @else if (postQuery.status() === 'error') {
36 Error: {{ postQuery.error()?.message }}
37 }
38 @if (postQuery.data(); as post) {
39 <h1>{{ post.title }}</h1>
40 <div>
41 <p>{{ post.body }}</p>
42 </div>
43 @if (postQuery.isFetching()) {
44 Background Updating...
45 }
46 }
47 </div>
48 `,
49})
50export class PostComponent {
51 @Output() setPostId = new EventEmitter<number>()
52​
53 // Until Angular supports signal-based inputs, we have to set a signal
54 @Input({ required: true, alias: 'postId' })
55 set _postId(value: number) {
56 this.postId.set(value)
57 }
58 postId = signal(0)
59 httpClient = inject(HttpClient)
60​
61 getPost$ = (postId: number) => {
62 return this.httpClient.get<Post>(
63 `https://jsonplaceholder.typicode.com/posts/${postId}`,
64 )
65 }
66​
67 postQuery = injectQuery(() => ({
68 enabled: this.postId() > 0,
69 queryKey: ['post', this.postId()],
70 queryFn: async (context): Promise<Post> => {
71 // Cancels the request when component is destroyed before the request finishes
72 const abort$ = fromEvent(context.signal, 'abort')
73 return lastValueFrom(this.getPost$(this.postId()).pipe(takeUntil(abort$)))
74 },
75 }))
76​
77 queryClient = injectQueryClient()
79​
80@Component({
81 changeDetection: ChangeDetectionStrategy.OnPush,
82 selector: 'posts',
83 standalone: true,
84 template: `<div>
85 <h1>Posts</h1>
86 @switch (postsQuery.status()) {
87 @case ('pending') {
88 Loading...
89 }
90 @case ('error') {
91 Error: {{ postsQuery.error()?.message }}
92 }
93 @default {
94 <div class="todo-container">
95 @for (post of postsQuery.data(); track post.id) {
96 <p>
97 <!-- We can access the query data here to show bold links for-->
98 <!-- ones that are cached-->
99 <a
100 href="#"
101 (click)="setPostId.emit(post.id)"
102 [style]="
103 queryClient.getQueryData(['post', post.id])
104 ? {
105 fontWeight: 'bold',
106 color: 'green'
107 }
108 : {}
109 "
110 >{{ post.title }}</a
111 >
112 </p>
113 }
114 </div>
115 }
116 }
117 <div>
118 @if (postsQuery.isFetching()) {
119 Background Updating...
120 }
121 </div>
122 </div> `,
123})
124export class PostsComponent {
125 @Output() setPostId = new EventEmitter<number>()
126​
127 posts$ = inject(HttpClient).get<Array<Post>>(
128 'https://jsonplaceholder.typicode.com/posts',
129 )
130​
131 postsQuery = injectQuery(() => ({
132 queryKey: ['posts'],
133 queryFn: () => lastValueFrom(this.posts$),
134 }))
135​
136 queryClient = injectQueryClient()
138​
139@Component({
140 changeDetection: ChangeDetectionStrategy.OnPush,
141 selector: 'basic-example',
142 standalone: true,
143 template: `
144 <p>
145 As you visit the posts below, you will notice them in a loading state the
146 first time you load them. However, after you return to this list and click
147 on any posts you have already visited again, you will see them load
148 instantly and background refresh right before your eyes!
149 <strong>
150 (You may need to throttle your network speed to simulate longer loading
151 sequences)
152 </strong>
153 </p>
154 <angular-query-devtools initialIsOpen />
155 @if (postId() > -1) {
156 <post [postId]="postId()" (setPostId)="postId.set($event)"></post>
157 } @else {
158 <posts (setPostId)="postId.set($event)" />
159 }
160 `,
161 imports: [AngularQueryDevtools, PostComponent, PostsComponent],
162})
163export class BasicExampleComponent {
164 postId = signal(-1)