Sub topic 2
What Happens When an Observable Errors or Completes
Assume you know Angular components, dependency injection, signals, and basic RxJS operators. This chapter focuses on how toSignal handles the end and failure of an observable, then introduces toObservable.
Errors and completion in `toSignal`
toSignal subscribes to its source observable. If the source emits an error, reading the signal throws that error. Handle expected failures inside the RxJS pipeline so the signal remains readable.
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable, catchError, of } from 'rxjs';
export function safeSignal(source$: Observable<string>) {
return toSignal(
source$.pipe(catchError(() => of('fallback'))),
{ initialValue: 'loading' },
);
}If the observable completes, toSignal keeps its most recent value. The signal does not expose a separate “completed” state. The subscription simply stops receiving values.
Automatic unsubscription and manual cleanup
By default, toSignal connects the subscription to the current Angular injection context. When that context is destroyed, Angular unsubscribes automatically. For a component, this normally means cleanup when the component is removed.
The manualCleanup: true option prevents Angular from managing unsubscription. The observable must then complete or error on its own, or you must manage its lifetime another way. Use this option mainly for finite observables. A long-lived source can otherwise keep resources alive after the component is gone.
Turning a signal into an observable
toObservable exposes signal changes as an RxJS observable. It uses an Angular effect internally, so emissions happen asynchronously after the signal has stabilized.
import { Component, signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-demo',
template: '',
})
export class Demo {
n = signal(0);
n$ = toObservable(this.n);
}If n.set(1) and n.set(2) occur in the same synchronous turn, subscribers usually receive only the stabilized value, 2. Use toObservable when RxJS operators or subscription-based APIs are more useful than direct signal reads.
Exercise
What should you do if a source observable can fail but the template needs a readable signal?
Show answer
Handle the failure with catchError before passing the observable to toSignal, and emit a fallback value.