Sub topic 5
What happens when the observable errors or completes
This chapter assumes you can create components and inject services, read and write signals, and use basic RxJS operators such as map, switchMap and catchError. It also assumes you know that toSignal from @angular/core/rxjs-interop subscribes to an observable and exposes the latest value as a signal.
A signal always holds a value. An observable can end in three ways: it can emit values forever, it can complete, or it can error. A signal has no concept of "the stream ended". toSignal has to map those two endings onto a plain value holder, and the mapping has consequences you need to know before you ship it.
The three states behind a `toSignal` signal
Internally, the signal returned by toSignal is a read-only wrapper over a small state object. At any moment that state is one of three things:
- No value yet. The observable has not emitted. Reading the signal gives
undefined, or yourinitialValueif you provided one. - A value. The last emitted value. Each
nextreplaces it. - An error. The observable called
error. Reading the signal rethrows that error.
There is no fourth state for "completed". Completion changes nothing visible.
Errors: the signal throws when you read it
When the source observable errors, toSignal does not catch the error and does not throw at the moment it happens. It stores the error. The next time anything reads the signal, the read throws that same error.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { throwError } from 'rxjs';
@Component({
selector: 'app-broken',
template: `<p>{{ data() }}</p>`,
})
export class Broken {
// The observable errors immediately. Reading data() throws Error('boom').
data = toSignal(
throwError(() => new Error('boom')),
{ initialValue: 'loading' },
);
}Three details matter here.
initialValuedoes not protect you. It covers the time before the first emission. Once the error arrives, it is replaced by the error state, and the initial value is gone.- The error is permanent. An observable that has errored is finished. It will never emit again, so the signal can never recover. Every later read throws the same error object.
- The failure appears where the signal is read. In the example, Angular throws while rendering the template, and the error goes to the application's
ErrorHandler. If acomputedreads the errored signal, the computed also throws, and so does anything that reads the computed. Aneffectthat reads it fails inside the effect.
This differs from subscribe, where an unhandled error is reported through RxJS's global error reporting and nothing else breaks. With toSignal, the error becomes a rendering or computation failure, which is usually more disruptive.
You can also catch it yourself:
import { signal } from '@angular/core';
function readSafely(source: () => string): string {
try {
return source();
} catch {
return 'unavailable';
}
}
const failing = signal('x');
console.log(readSafely(failing)); // "x"The try/catch approach works but scatters error handling across every read site. The better design is to handle the error in the observable before it reaches toSignal.
Completion: the last value stays
When the observable completes, toSignal ignores it. The signal keeps the last emitted value indefinitely, and nothing tells readers that the source is finished.
import { Injector, inject, runInInjectionContext } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { of } from 'rxjs';
export function demoCompletion(): void {
const injector = inject(Injector);
runInInjectionContext(injector, () => {
// of() emits 1, 2, 3 synchronously, then completes.
const last = toSignal(of(1, 2, 3));
console.log(last()); // 3, and it stays 3
});
}Notice the type of last. Without initialValue or requireSync, it is Signal<number | undefined>, because the observable might not have emitted yet. Here it happened to emit synchronously, but the compiler cannot know that.
Completion without any emission is the edge case:
| Source behavior | Options | Signal value | Notes |
|---|---|---|---|
| Emits, then completes | none | last emitted value | Type includes `undefined` |
| Completes with no emission | none | `undefined` | Looks the same as "not loaded yet" |
| Completes with no emission | `initialValue: x` | `x` | Stays `x` forever |
| Completes with no emission | `requireSync: true` | not applicable | `toSignal` throws at creation, because no synchronous value arrived |
| Errors | any | not applicable | Reads throw the error |
The completion case that surprises people most is EMPTY or a take(0)-style pipeline with no initialValue. The signal reads undefined forever, which is indistinguishable from a request that has not answered. If "finished with nothing" must differ from "still waiting", encode that difference in the value, as shown in the next section.
Handling errors before they reach the signal
The fix is to make the observable infallible by the time toSignal subscribes. There are three common ways.
Replace the error with a fallback value
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable, catchError, of } from 'rxjs';
// Call this from an injection context, such as a field initializer or constructor.
export function safeSignal(source$: Observable<string>) {
return toSignal(
source$.pipe(catchError(() => of('fallback'))),
{ initialValue: 'loading' },
);
}catchError swaps the failing stream for of('fallback'). The signal receives 'fallback' as an ordinary value and then the replacement completes, which, as described above, leaves 'fallback' in place. This is simple, but the template cannot tell a real value from the fallback.
Model the status explicitly
When the UI must show an error message, put the status in the value. This is the most common production pattern.
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, map, of } from 'rxjs';
type LoadState<T> =
| { status: 'loading' }
| { status: 'success'; value: T }
| { status: 'error'; message: string };
@Component({
selector: 'app-user-list',
template: `
@let s = state();
@if (s.status === 'loading') {
<p>Loading...</p>
} @else if (s.status === 'error') {
<p>Could not load users: {{ s.message }}</p>
} @else {
<ul>
@for (u of s.value; track u) {
<li>{{ u }}</li>
}
</ul>
}
`,
})
export class UserList {
private http = inject(HttpClient);
state = toSignal(
this.http.get<string[]>('/api/users').pipe(
map((value): LoadState<string[]> => ({ status: 'success', value })),
catchError((err: unknown) =>
of<LoadState<string[]>>({
status: 'error',
message: err instanceof Error ? err.message : 'Request failed',
}),
),
),
{ initialValue: { status: 'loading' } as LoadState<string[]> },
);
}The component needs provideHttpClient() in the application configuration. The signal never throws, the template handles all three cases, and TypeScript narrows s in each branch. The cost is a little more code per data source.
Retry before giving up
For transient failures, add retry before catchError. retry resubscribes to the source on error, so it only helps with cold observables such as HTTP calls.
import { Observable, catchError, of, retry } from 'rxjs';
export function resilient(request$: Observable<string[]>): Observable<string[]> {
return request$.pipe(
retry({ count: 2, delay: 500 }), // two more attempts, 500 ms apart
catchError(() => of([] as string[])),
);
}Pass the result to toSignal as usual.
Where to put `catchError` in a longer pipeline
An error ends an observable. In a pipeline that feeds a signal through toObservable, switchMap and toSignal, where you place catchError decides whether one failure kills the whole pipeline.
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, debounceTime, of, switchMap } from 'rxjs';
@Component({
selector: 'app-search-safe',
template: `
<input (input)="query.set($any($event.target).value)" />
<p>{{ results().length }} results</p>
`,
})
export class SearchSafe {
private http = inject(HttpClient);
query = signal('');
results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
switchMap((q) =>
this.http.get<string[]>('/api/search', { params: { q } }).pipe(
// Inside switchMap: only this request is replaced on failure.
catchError(() => of([] as string[])),
),
),
),
{ initialValue: [] as string[] },
);
}If you moved catchError after switchMap, a single failed request would turn into [], then the outer stream would complete. Further typing would never trigger another search, and the signal would be stuck on its last value with no sign of a problem. Putting catchError inside switchMap keeps the outer subscription alive, so the next query still runs.
Completion and `toObservable`
The reverse direction behaves differently. A signal cannot error and cannot complete by itself, so toObservable never emits an error. Its observable completes when the injection context is destroyed, for example when the component is destroyed. Downstream operators such as takeUntil or finalize will run at that point.
Checklist for sources that can fail
- Does the source ever error? HTTP calls, WebSocket streams and anything using
throwErrordo. Handle it beforetoSignal. - Is there a real difference between "no data" and "not loaded"? If so, use a status object instead of
undefined. - Is the
catchErrorinside the inner observable ofswitchMap,mergeMaporexhaustMap, so the outer stream survives? - Does the source complete? Remember that the signal keeps the final value and gives no hint that updates have stopped.
Summary
- An erroring source leaves the signal permanently throwing on read.
initialValuedoes not prevent this. - A completing source leaves the signal at its last value, with no notification. A source that completes without emitting leaves
undefinedor yourinitialValue. - Handle errors in the observable with
catchError, preferably producing an explicit status value. - In longer pipelines, put
catchErroron the inner observable so the outer stream keeps running.
Exercise
A component declares price = toSignal(this.http.get<number>('/api/price'), { initialValue: 0 }). The server returns a 500 error. What does the template show when it reads price(), and what change would make the template show 0 instead?
Show answer
The template does not show 0. The HTTP observable errors, so the signal enters its error state, and reading price() throws the HttpErrorResponse during rendering, which goes to the ErrorHandler. initialValue only applies before the first emission. To show 0, handle the error in the pipe: this.http.get<number>('/api/price').pipe(catchError(() => of(0))). For a visible error message, map to a status object such as { status: 'error', message } instead.
Exercise
You write toSignal(toObservable(this.query).pipe(debounceTime(300), switchMap(q => this.http.get<string[]>('/api/search', { params: { q } })), catchError(() => of([] as string[]))), { initialValue: [] as string[] }). The first search request fails. What happens to later searches, and where should catchError go?
Show answer
The failure propagates out of switchMap to the outer catchError, which emits [] and then the outer observable completes. After that, typing no longer triggers searches, and the signal stays at [] with no error shown. Move catchError inside the switchMap callback, on the http.get(...) observable, so only that request is replaced and the outer stream continues.
Exercise
const s = toSignal(of(1, 2, 3).pipe(delay(0), take(0))). What is s() after one second, and what is its type?
Show answer
take(0) completes immediately without emitting, and with no initialValue the signal keeps its default, so s() is undefined. The type is Signal<number | undefined>. Completion does not change the signal, and nothing distinguishes this case from "not loaded yet". Use an initialValue or a status object if that difference matters.