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

queries.ts

29 lines857 Bytes

1import { Injectable, inject } from '@angular/core'
2import { queryOptions } from '@tanstack/angular-query'
3import { fromEvent, lastValueFrom, takeUntil } from 'rxjs'
4import { PostsAPI } from './api'
5​
6@Injectable({
7 providedIn: 'root',
8})
9export class PostsQueries {
10 readonly #api = inject(PostsAPI)
11​
12 all = () => ['posts'] as const
13​
14 list = () =>
15 queryOptions({
16 queryKey: [...this.all(), 'list'] as const,
17 queryFn: () => lastValueFrom(this.#api.getPosts()),
18 })
19​
20 detail = (id: number) =>
21 queryOptions({
22 queryKey: [...this.all(), 'detail', id] as const,
23 queryFn: (context) => {
24 // Cancels the request when component is destroyed before the request finishes
25 const abort$ = fromEvent(context.signal, 'abort')
26 return lastValueFrom(this.#api.getPost(id).pipe(takeUntil(abort$)))
27 },
28 })