Skip to content

Instantly share code, notes, and snippets.

@Armenvardanyan95
Created November 21, 2024 08:44
Show Gist options
  • Save Armenvardanyan95/5713032fedc46be45024bb7897f53712 to your computer and use it in GitHub Desktop.
Save Armenvardanyan95/5713032fedc46be45024bb7897f53712 to your computer and use it in GitHub Desktop.
@Component({
template: ``
@if (post.isLoading()) {
<span>Loading...</span>
} @else if (post.hasValue()) {
<h1>{{ post.value()!.title }}</h1>
<p>{{ post.value()!.body }}</p>
@if (author.hasValue()) {
<div>
<span>Author: </span>
<span>{{ author.value()!.name }}</span>
</div>
}
} @else if (post.error()) {
<span>Error loading post: {{ post.error() }}</span>
<button (click)="post.reload()">Retry</button>
}
``,
})
export class PostComponent {
readonly #http = inject(HttpClient);
postId = input.required<number>();
post = rxResource({
request: () => ({ id: this.postId() }),
loader: () =>
this.#http.get<Post>(
`https://jsonplaceholder.typicode.com/posts/${this.postId()}`
),
});
author = rxResource({
request: () => ({ id: this.post.value()?.userId }),
loader: (id) => {
if (id) {
return this.#http.get<User>(
`https://jsonplaceholder.typicode.com/users/${id}`
);
}
return of(null);
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment