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

posts.component.ts

69 lines1.6 KB

1import { Component, inject } from '@angular/core'
2import { injectQuery } from '@tanstack/angular-query'
3import { lastValueFrom } from 'rxjs'
4import { PostsService } from '../services/posts.service'
5​
6@Component({
7 selector: 'posts',
8 template: `
9 @if (postsQuery.isPending()) {
10 <p>Loading posts...</p>
11 } @else if (postsQuery.isError()) {
12 <p>Failed to load posts.</p>
13 } @else {
14 <section class="grid">
15 @for (post of postsQuery.data(); track post.id) {
16 <article class="card">
17 <p class="meta">Post #{{ post.id }}</p>
18 <h2>{{ post.title }}</h2>
19 <p>{{ post.body }}</p>
20 </article>
21 }
22 </section>
23 }
24 `,
25 styles: `
26 .grid {
27 display: grid;
28 gap: 16px;
29 grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
30 }
31​
32 .card {
33 padding: 20px;
34 border: 1px solid #eadfcb;
35 border-radius: 18px;
36 background: #fffdf8;
37 box-shadow: 0 12px 30px rgba(123, 88, 31, 0.08);
38 }
39​
40 .meta {
41 margin: 0 0 10px;
42 font-size: 12px;
43 font-weight: 700;
44 letter-spacing: 0.08em;
45 text-transform: uppercase;
46 color: #8b5e34;
47 }
48​
49 h2 {
50 margin: 0 0 10px;
51 font-size: 1.1rem;
52 line-height: 1.3;
53 }
54​
55 p {
56 margin: 0;
57 line-height: 1.5;
58 color: #374151;
59 }
60 `,
61})
62export class PostsComponent {
63 readonly #postsService = inject(PostsService)
64​
65 readonly postsQuery = injectQuery(() => ({
66 queryKey: ['posts'],
67 queryFn: () => lastValueFrom(this.#postsService.allPosts$()),
68 }))