Lab 16: httpResource
📖 Resources
Section titled “📖 Resources”🚀 Starter Code
Section titled “🚀 Starter Code”step-15-album-wholesale-v21-post-signal-computed
Continue from your Lab 15 result. If you need a fresh copy, use step-15-album-wholesale-v21-post-signal-computed as your base and complete Lab 15 first.
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
Section titled “📝 Instructions”Step 1: Create httpResource in AlbumService
Section titled “Step 1: Create httpResource in AlbumService”httpResource is imported from @angular/common/http (not @angular/core). It takes a function that returns a URL or request object:
import { httpResource } from '@angular/common/http';import { Injectable, signal } from '@angular/core';import { Album } from '../model/album.model';
@Injectable({ providedIn: 'root' })export class AlbumService { private refreshTrigger = signal(0);
// Declarative resource — reloads whenever refreshTrigger changes albums = httpResource<Album[]>(() => ({ url: 'http://localhost:3000/albums', params: { _t: this.refreshTrigger() } }));
refresh() { this.refreshTrigger.update(v => v + 1); }}Step 2: Access the Resource in a Component
Section titled “Step 2: Access the Resource in a Component”export class AlbumListComponent { private albumService = inject(AlbumService); albumsResource = this.albumService.albums;}Template:
@if (albumsResource.isLoading()) { <p>Loading...</p>}
@if (albumsResource.error()) { <p>Error loading albums</p>}
@if (albumsResource.value(); as albums) { @for (album of albums; track album.id) { <app-album-card [album]="album"></app-album-card> }}Step 3: Trigger a Refresh
Section titled “Step 3: Trigger a Refresh”Add a refresh button that reloads data without navigating:
<button mat-button (click)="albumService.refresh()">Refresh</button>The refreshTrigger signal causes httpResource to re-fetch automatically.
Step 4: Remove Manual Subscriptions
Section titled “Step 4: Remove Manual Subscriptions”Replace any this.http.get(...).subscribe(...) or toSignal(this.albumService.findAll()) patterns with the resource. The resource manages its own lifecycle — no need to unsubscribe.

