Skip to content

Commit c85b2c6

Browse files
committed
feat(challenge 59): added lazy loading for posts
1 parent 99a3647 commit c85b2c6

File tree

2 files changed

+45
-13
lines changed

2 files changed

+45
-13
lines changed

apps/angular/59-content-projection-defer/src/app/expandable-card.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
1+
import {
2+
ChangeDetectionStrategy,
3+
Component,
4+
effect,
5+
output,
6+
signal,
7+
} from '@angular/core';
28

39
@Component({
410
selector: 'app-expandable-card',
@@ -51,4 +57,10 @@ import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
5157
})
5258
export class ExpandableCard {
5359
public isExpanded = signal(false);
60+
expanded = output<boolean>();
61+
constructor() {
62+
effect(() => {
63+
this.expanded.emit(this.isExpanded());
64+
});
65+
}
5466
}
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1-
import { httpResource } from '@angular/common/http';
1+
import { httpResource, HttpResourceRef } from '@angular/common/http';
22
import {
33
ChangeDetectionStrategy,
44
Component,
5+
inject,
6+
Injector,
57
ResourceStatus,
8+
signal,
69
} from '@angular/core';
10+
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
711
import { ExpandableCard } from './expandable-card';
812

913
interface Post {
@@ -17,16 +21,18 @@ interface Post {
1721
selector: 'app-page-2',
1822
template: `
1923
page2
20-
<app-expandable-card>
24+
<app-expandable-card (expanded)="triggerFetch.set($event)">
2125
<div title>Load Post</div>
2226
<div>
23-
@if (postRessource.isLoading()) {
24-
Loading...
25-
} @else if (postRessource.status() === ResourceStatus.Error) {
26-
Error...
27-
} @else {
28-
@for (post of postRessource.value(); track post.id) {
29-
<div>{{ post.title }}</div>
27+
@if (postRessource) {
28+
@if (postRessource.isLoading()) {
29+
Loading...
30+
} @else if (postRessource.status() === ResourceStatus.Error) {
31+
Error...
32+
} @else {
33+
@for (post of postRessource.value(); track post.id) {
34+
<div>{{ post.title }}</div>
35+
}
3036
}
3137
}
3238
</div>
@@ -36,8 +42,22 @@ interface Post {
3642
imports: [ExpandableCard],
3743
})
3844
export class Page2 {
39-
public postRessource = httpResource<Post[]>(
40-
'https://jsonplaceholder.typicode.com/posts',
41-
);
45+
public postRessource: HttpResourceRef<Post[] | undefined> | null = null;
46+
protected triggerFetch = signal(false);
47+
#injector = inject(Injector);
48+
constructor() {
49+
toObservable(this.triggerFetch)
50+
.pipe(takeUntilDestroyed())
51+
.subscribe((trigger) => {
52+
if (trigger) {
53+
this.postRessource = httpResource<Post[]>(
54+
'https://jsonplaceholder.typicode.com/posts',
55+
{
56+
injector: this.#injector,
57+
},
58+
);
59+
}
60+
});
61+
}
4262
protected readonly ResourceStatus = ResourceStatus;
4363
}

0 commit comments

Comments
 (0)