Open History to see the last commit
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 templateUrl: './post.component.html',
16})
17export class PostComponent {
18 readonly #postsService = inject(PostsService)
19β
20 readonly setPostId = output<number>()
21 readonly postId = input(0)
22β
23 readonly postQuery = injectQuery(() => ({
24 enabled: this.postId() > 0,
25 queryKey: ['post', this.postId()],
26 queryFn: (context) => {
27 // Cancels the request when component is destroyed before the request finishes
28 const abort$ = fromEvent(context.signal, 'abort')
29 return lastValueFrom(
30 this.#postsService.postById$(this.postId()).pipe(takeUntil(abort$)),
31 )
32 },
33 }))
34}