Lab 13: toSignal()
π Resourcesβ
π Starter Codeβ
step-13-album-wholesale-v21-post-standalone-control-flow
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β
Step 1: Convert Observable to Signalβ
toSignal() converts an Observable to a Signal:
import { toSignal } from '@angular/core/rxjs-interop';
// Before: Observable
albums$ = this.albumService.getAlbums();
// After: Signal
albums = 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β
Replace BehaviorSubject with signal():
// Before: BehaviorSubject
private isAuthenticatedSubject = new BehaviorSubject<boolean>(false);
isAuthenticated$ = this.isAuthenticatedSubject.asObservable();
// After: Signal
private isAuthenticatedSignal = signal<boolean>(false);
isAuthenticated = this.isAuthenticatedSignal.asReadonly();
Update methods:
// Before
this.isAuthenticatedSubject.next(true);
// After
this.isAuthenticatedSignal.set(true);