Sub topic 5
What happens when the observable errors or completes
This chapter assumes you know how toSignal subscribes to an observable and how initialValue works. Observables can end in two ways, by completing or by erroring. Signals have no notion of either, so toSignal has to map each ending onto something a signal can express.
Completion keeps the last value
When the source completes, the signal does not reset or become undefined. It keeps the last value it received. The subscription is finished, so the value never changes again.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { of } from 'rxjs';
@Component({
selector: 'app-done',
template: `<p>Last: {{ last() }}</p>`,
})
export class Done {
// of() emits 1, 2, 3 and completes. The signal ends at 3.
last = toSignal(of(1, 2, 3), { initialValue: 0 });
}If the source completes without ever emitting, the signal stays at its initialValue. Without an initialValue, it stays undefined. With requireSync, a source that completes without emitting is a failure, because no synchronous value arrived.
An error is rethrown when you read the signal
When the source errors, toSignal stores the error. The next time any code reads the signal, the read throws that error. The error does not surface at the moment it happens. It surfaces at the read site, such as a template binding, a computed(), or an effect().
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { throwError } from 'rxjs';
@Component({
selector: 'app-broken',
template: `<p>{{ describe() }}</p>`,
})
export class Broken {
data = toSignal(throwError(() => new Error('boom')), { initialValue: 'none' });
describe(): string {
try {
return this.data();
} catch (e) {
return 'caught: ' + (e as Error).message;
}
}
}Two details matter here:
- The signal stays in the error state. The source has terminated, so the signal never recovers. Every later read throws the same error.
- A
computed()that reads the failing signal also throws. Angular caches the error in the computed and rethrows it on reads. An unguarded read in a template makes the whole binding fail.
The states a toSignal signal can be in look like this:
Handling errors before they reach the signal
Because an error is permanent and throws on read, the usual fix is to handle it inside the observable pipeline, before toSignal sees it. Use catchError to replace the failure with a value. Use retry if the operation can be tried again.
A useful pattern turns the result into a small state object. The template then reads the state and never has to catch an exception.
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, map, of, retry } from 'rxjs';
type Result =
| { status: 'loading' }
| { status: 'ok'; items: string[] }
| { status: 'error'; message: string };
@Component({
selector: 'app-items',
template: `
@switch (result().status) {
@case ('loading') { <p>Loading...</p> }
@case ('error') { <p>Failed to load.</p> }
@default { <p>Loaded.</p> }
}
`,
})
export class Items {
private http = inject(HttpClient);
result = toSignal(
this.http.get<string[]>('/api/items').pipe(
retry(2),
map((items): Result => ({ status: 'ok', items })),
catchError((err) => of<Result>({ status: 'error', message: String(err.message) })),
),
{ initialValue: { status: 'loading' } as Result },
);
}catchError returns of(...), which emits once and completes. The signal then holds the error state as an ordinary value, and reads never throw.
Note that retry(2) sits before catchError. The retry resubscribes to the HTTP call, and only after the retries are used up does the error reach catchError.
Choosing a strategy
| Situation | Approach | Result when reading the signal |
|---|---|---|
| Source may fail and the UI should show a message | `catchError` mapping to a state object | Always returns a value |
| Source may fail and a default is acceptable | `catchError(() => of(default))` | Returns the default |
| Failure is a bug that should be loud | No handling | Read throws, and Angular's `ErrorHandler` sees it |
| Source is a one-shot request | Completion is expected | Keeps the final value |
What about toObservable?
Signals cannot error, so an observable from toObservable never errors. It completes when the injection context it was created in is destroyed, for example when the component is destroyed. Operators downstream, such as switchMap with an HTTP call, can still error. Handle those errors inside the inner observable with catchError. That way one failed request does not end the whole stream.
Exercise
A component has user = toSignal(this.http.get<User>('/api/user'), { initialValue: null }). The request fails with a 500 error. What happens when the template reads user(), and how do you make the signal hold null instead?
Show answer
Reading user() throws the HTTP error, and it keeps throwing on every read because the source has already terminated. To keep null, add catchError(() => of(null)) in the pipe before toSignal, so the error becomes a normal emitted value and the observable completes.