diff --git a/apps/angular/59-content-projection-defer/src/app/page-2.ts b/apps/angular/59-content-projection-defer/src/app/page-2.ts index 3f2886d4e..feb56c2e8 100644 --- a/apps/angular/59-content-projection-defer/src/app/page-2.ts +++ b/apps/angular/59-content-projection-defer/src/app/page-2.ts @@ -2,7 +2,13 @@ import { httpResource } from '@angular/common/http'; import { ChangeDetectionStrategy, Component, + computed, + EnvironmentInjector, + inject, + InjectionToken, ResourceStatus, + runInInjectionContext, + viewChild, } from '@angular/core'; import { ExpandableCard } from './expandable-card'; @@ -13,6 +19,12 @@ interface Post { userId: number; } +const PostResources = new InjectionToken('Fetch Post resources', { + providedIn: 'root', + factory: () => + httpResource('https://jsonplaceholder.typicode.com/posts'), +}); + @Component({ selector: 'app-page-2', template: ` @@ -20,12 +32,12 @@ interface Post {
Load Post
- @if (postRessource.isLoading()) { + @if (postResource()?.isLoading()) { Loading... - } @else if (postRessource.status() === ResourceStatus.Error) { + } @else if (postResource()?.status() === ResourceStatus.Error) { Error... } @else { - @for (post of postRessource.value(); track post.id) { + @for (post of postResource()?.value(); track post.id) {
{{ post.title }}
} } @@ -36,8 +48,18 @@ interface Post { imports: [ExpandableCard], }) export class Page2 { - public postRessource = httpResource( - 'https://jsonplaceholder.typicode.com/posts', - ); + private readonly environmentInjector = inject(EnvironmentInjector); + + private expandableCard = viewChild(ExpandableCard); + + protected postResource = computed(() => { + if (this.expandableCard()?.isExpanded()) { + return runInInjectionContext(this.environmentInjector, () => { + return inject(PostResources); + }); + } + return undefined; + }); + protected readonly ResourceStatus = ResourceStatus; }