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

queries.md

112 lines2.6 KB

1---
2id: queries
3title: Queries
4ref: docs/framework/react/guides/queries.md
5replace:
6 {
7 'React': 'Angular',
8 'react-query': 'angular-query',
9 '@tanstack/angular-query': '@tanstack/angular-query',
10 'promise': 'promise or observable',
11 'custom hooks': 'services',
12 'the `useQuery` hook': '`injectQuery`',
13 '`useQuery`': '`injectQuery`',
14 "TypeScript will also narrow the type of data correctly if you've checked for pending and error before accessing it.": 'TypeScript will only narrow the type when checking boolean signals such as `isPending` and `isError`.',
15 }
16---
17​
18[//]: # 'Example'
19​
20```ts
21import { injectQuery } from '@tanstack/angular-query'
22​
23export class TodosComponent {
24 readonly todosQuery = injectQuery(() => ({
25 queryKey: ['todos'],
26 queryFn: fetchTodoList,
27 }))
29```
30​
31[//]: # 'Example'
32[//]: # 'Example2'
33​
34```ts
35todosQuery = injectQuery(() => ({
36 queryKey: ['todos'],
37 queryFn: fetchTodoList,
38}))
39```
40​
41[//]: # 'Example2'
42[//]: # 'Example3'
43​
44```angular-ts
45@Component({
46 selector: 'todos',
47 template: `
48 @if (todosQuery.isPending()) {
49 <span>Loading...</span>
50 } @else if (todosQuery.isError()) {
51 <span>Error: {{ todosQuery.error()?.message }}</span>
52 } @else {
53 <!-- We can assume by this point that status === 'success' -->
54 @for (todo of todosQuery.data(); track todo.id) {
55 <li>{{ todo.title }}</li>
56 } @empty {
57 <li>No todos found</li>
58 }
59 }
60 `,
61})
62export class PostsComponent {
63 readonly todosQuery = injectQuery(() => ({
64 queryKey: ['todos'],
65 queryFn: fetchTodoList,
66 }))
68```
69​
70[//]: # 'Example3'
71​
72If booleans aren't your thing, you can always use the `status` state as well:
73​
74[//]: # 'Example4'
75​
76```angular-ts
77@Component({
78 selector: 'todos',
79 template: `
80 @switch (todosQuery.status()) {
81 @case ('pending') {
82 <span>Loading...</span>
83 }
84 @case ('error') {
85 <span>Error: {{ todosQuery.error()?.message }}</span>
86 }
87 <!-- also status === 'success', but "else" logic works, too -->
88 @default {
89 <ul>
90 @for (todo of todosQuery.data(); track todo.id) {
91 <li>{{ todo.title }}</li>
92 } @empty {
93 <li>No todos found</li>
94 }
95 </ul>
96 }
97 }
98 `,
99})
100class TodosComponent {}
101```
102​
103[//]: # 'Example4'
104[//]: # 'Materials'
105​
106Angular Query can convert each query result into a Resource-compatible view with `toResource`. See
107the [Resource API](../resource-api.md) when an Angular API expects a
108[Resource](https://angular.dev/api/core/Resource).
109​
110[//]: # 'Materials'
111​
112See [Error handling](./error-handling.md) to connect cache failures to Angular’s `ErrorHandler`.