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

tasks.service.ts

59 lines1.6 KB

1import { HttpClient } from '@angular/common/http'
2import { Injectable, inject } from '@angular/core'
3import {
4 QueryClient,
5 mutationOptions,
6 queryOptions,
7} from '@tanstack/angular-query-experimental'
8​
9import { lastValueFrom } from 'rxjs'
10​
11@Injectable({
12 providedIn: 'root',
13})
14export class TasksService {
15 readonly #queryClient = inject(QueryClient) // Manages query state and caching
16 readonly #http = inject(HttpClient) // Handles HTTP requests
17​
18 /**
19 * Fetches all tasks from the API.
20 * Returns an observable containing an array of task strings.
21 */
22 allTasks = (intervalMs: number) =>
23 queryOptions({
24 queryKey: ['tasks'],
25 queryFn: () => {
26 return lastValueFrom(this.#http.get<Array<string>>('/api/tasks'))
27 },
28 refetchInterval: intervalMs,
29 })
30​
31 /**
32 * Creates a mutation for adding a task.
33 * On success, invalidates and refetches the "tasks" query cache to update the task list.
34 */
35 addTask() {
36 return mutationOptions({
37 mutationFn: (task: string) =>
38 lastValueFrom(this.#http.post('/api/tasks', task)),
39 mutationKey: ['tasks'],
40 onSuccess: () => {
41 this.#queryClient.invalidateQueries({ queryKey: ['tasks'] })
42 },
43 })
44 }
45​
46 /**
47 * Creates a mutation for clearing all tasks.
48 * On success, invalidates and refetches the "tasks" query cache to ensure consistency.
49 */
50 clearAllTasks() {
51 return mutationOptions({
52 mutationFn: () => lastValueFrom(this.#http.delete('/api/tasks')),
53 mutationKey: ['clearTasks'],
54 onSuccess: () => {
55 this.#queryClient.invalidateQueries({ queryKey: ['tasks'] })
56 },
57 })
58 }