Lab 12: toSignal()
📖 Resources
Section titled “📖 Resources”🚀 Starter Code
Section titled “🚀 Starter Code”step-12-album-wholesale-v21-pre-control-flow
Continue from your Lab 12 result. If starting fresh, use step-12-album-wholesale-v21-pre-control-flow as your base and complete Labs 11 and 12 first.
In this lab, you’ll convert RxJS observables to signals using toSignal(). You’ll transform observable streams into reactive signals, replace async pipes with signal calls in templates, and migrate BehaviorSubjects to writable signals.
📝 Instructions
Section titled “📝 Instructions”Step 1: Convert Observable to Signal
Section titled “Step 1: Convert Observable to Signal”toSignal() converts an Observable to a Signal:
import { toSignal } from '@angular/core/rxjs-interop';
// Before: Observablealbums$ = this.albumService.getAlbums();
// After: Signalalbums = toSignal(this.albumService.getAlbums(), { initialValue: [] });Template changes:
<!-- Before: async pipe -->@for (album of albums$ | async; track album.id) { <app-album-card [album]="album"></app-album-card>}
<!-- After: signal call -->@for (album of albums(); track album.id) { <app-album-card [album]="album"></app-album-card>}Step 2: Convert BehaviorSubject to Signal
Section titled “Step 2: Convert BehaviorSubject to Signal”Replace BehaviorSubject with signal():
// Before: BehaviorSubjectprivate isAuthenticatedSubject = new BehaviorSubject<boolean>(false);isAuthenticated$ = this.isAuthenticatedSubject.asObservable();
// After: Signalprivate isAuthenticatedSignal = signal<boolean>(false);isAuthenticated = this.isAuthenticatedSignal.asReadonly();Update methods:
// Beforethis.isAuthenticatedSubject.next(true);
// Afterthis.isAuthenticatedSignal.set(true);
