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

post.component.ts

35 lines992 Bytes

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