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

queries-service.ts

42 lines907 Bytes

1import { Injectable, inject } from '@angular/core'
2import { lastValueFrom } from 'rxjs'
3import { queryOptions } from '@tanstack/angular-query-experimental'
4import { HttpClient } from '@angular/common/http'
5​
6export interface Post {
7 id: number
8 title: string
9 body: string
11​
12@Injectable({
13 providedIn: 'root',
14})
15export class QueriesService {
16 private http = inject(HttpClient)
17​
18 post(postId: number) {
19 return queryOptions({
20 queryKey: ['post', postId],
21 queryFn: () => {
22 return lastValueFrom(
23 this.http.get<Post>(
24 `https://jsonplaceholder.typicode.com/posts/${postId}`,
25 ),
26 )
27 },
28 })
29 }
30​
31 posts() {
32 return queryOptions({
33 queryKey: ['posts'],
34 queryFn: () =>
35 lastValueFrom(
36 this.http.get<Array<Post>>(
37 'https://jsonplaceholder.typicode.com/posts',
38 ),
39 ),
40 })
41 }