Lab 16: httpResource
π Resourcesβ
π Starter Codeβ
step-16-album-wholesale-v21-post-signal-refactor-cart
In this lab, you'll simplify data fetching using the new httpResource API. You'll create declarative HTTP resources that automatically manage loading and error states, eliminate manual subscription management, and implement refresh triggers with signals.
π Instructionsβ
Step 1: Create httpResourceβ
httpResource provides declarative data loading with built-in loading/error states:
import { httpResource } from '@angular/core';
// Create resource
albums = httpResource<Album[], void>({
request: () => ({}),
loader: () => this.http.get<Album[]>('/api/albums')
});
// Access data
albums.value() // The data
albums.isLoading() // Loading state
albums.error() // Error state
Step 2: Use in Componentβ
export class AlbumListComponent {
private albumService = inject(AlbumService);
albumsResource = this.albumService.albums;
}
Template:
@if (albumsResource.isLoading()) {
<p>Loading...</p>
}
@if (albumsResource.error()) {
<p>Error: {{ albumsResource.error() }}</p>
}
@if (albumsResource.value(); as albums) {
@for (album of albums; track album.id) {
<app-album-card [album]="album"></app-album-card>
}
}
Step 3: Trigger Refreshβ
Use a trigger signal to reload data:
export class AlbumService {
private refreshTrigger = signal(0);
albums = httpResource({
request: () => ({ trigger: this.refreshTrigger() }),
loader: () => this.http.get<Album[]>(this.apiUrl)
});
refresh() {
this.refreshTrigger.update(v => v + 1);
}
}