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

post.component.ts

38 lines1.0 KB

1import {
2 ChangeDetectionStrategy,
3 Component,
4 EventEmitter,
5 Output,
6 inject,
7 input,
8} from '@angular/core'
9import { QueryClient, injectQuery } from '@tanstack/angular-query-experimental'
10import { fromEvent, lastValueFrom, takeUntil } from 'rxjs'
11import { PostsService } from '../services/posts-service'
12​
13@Component({
14 changeDetection: ChangeDetectionStrategy.OnPush,
15 selector: 'post',
16 templateUrl: './post.component.html',
17})
18export class PostComponent {
19 #postsService = inject(PostsService)
20​
21 @Output() setPostId = new EventEmitter<number>()
22​
23 postId = input(0)
24​
25 postQuery = injectQuery(() => ({
26 enabled: this.postId() > 0,
27 queryKey: ['post', this.postId()],
28 queryFn: async (context) => {
29 // Cancels the request when component is destroyed before the request finishes
30 const abort$ = fromEvent(context.signal, 'abort')
31 return lastValueFrom(
32 this.#postsService.postById$(this.postId()).pipe(takeUntil(abort$)),
33 )
34 },
35 }))
36​
37 queryClient = inject(QueryClient)