Skip to main content

Lab 16: httpResource

πŸ“– Resources​

πŸš€ 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​

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​

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​

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​

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.