Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions apps/angular/59-content-projection-defer/src/app/page-2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -13,19 +19,25 @@ interface Post {
userId: number;
}

const PostResources = new InjectionToken('Fetch Post resources', {
providedIn: 'root',
factory: () =>
httpResource<Post[]>('https://jsonplaceholder.typicode.com/posts'),
});

@Component({
selector: 'app-page-2',
template: `
page2
<app-expandable-card>
<div title>Load Post</div>
<div>
@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) {
<div>{{ post.title }}</div>
}
}
Expand All @@ -36,8 +48,18 @@ interface Post {
imports: [ExpandableCard],
})
export class Page2 {
public postRessource = httpResource<Post[]>(
'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, () => {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you should not use runInInjectionContext, this should always be avoided.

return inject(PostResources);
});
}
return undefined;
});

protected readonly ResourceStatus = ResourceStatus;
}