Sub topic 3
Turning an observable into a signal with toSignal
This chapter assumes you can create a component, use inject(), read signals with signal() and computed(), and write basic RxJS with map and switchMap. It covers the first direction of interop: observable to signal.
What toSignal does
toSignal comes from @angular/core/rxjs-interop. It subscribes to an observable right away and stores the latest emitted value in a read-only signal. Templates and computed() can then read that value like any other signal.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker',
template: `<p>Seconds: {{ seconds() }}</p>`,
})
export class Ticker {
seconds = toSignal(interval(1000), { initialValue: 0 });
}The subscription starts when the component is created, not when the template first reads the signal. Angular also unsubscribes when the component is destroyed, so you don't need async pipes or takeUntil.
The first value problem
A signal must always have a value, but an observable may not emit for a while. So toSignal has a choice to make before the first emission. By default it uses undefined, and the type becomes Signal<T | undefined>. You can remove undefined in two ways.
| Option | Type result | Use when | Column |
|---|---|---|---|
| none | `Signal<T \ | undefined>` | You can handle a missing value in the template |
| `initialValue: x` | `Signal<T>` | You have a sensible placeholder | |
| `requireSync: true` | `Signal<T>` | The source emits synchronously on subscribe |
requireSync suits sources like BehaviorSubject, which emit as soon as you subscribe.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-counter',
template: `<p>{{ count() }}</p>`,
})
export class Counter {
private count$ = new BehaviorSubject(0);
count = toSignal(this.count$, { requireSync: true });
}Errors and completion
The two end states of an observable behave differently.
- Completion: the signal keeps the last emitted value. Nothing breaks.
- Error:
toSignalstores the error. The next time you read the signal, it throws that error. In a template this surfaces as a rendering error.
Handle errors inside the pipe, before the observable reaches toSignal. This turns the failure into a normal value.
import { Observable, catchError, of } from 'rxjs';
import { toSignal } from '@angular/core/rxjs-interop';
export function safeSignal(source$: Observable<string>) {
// Must run in an injection context, such as a field initializer or constructor.
return toSignal(
source$.pipe(catchError(() => of('fallback'))),
{ initialValue: 'loading' },
);
}Note that catchError replaces the failed stream with of('fallback'). The original source is not retried, so the signal ends on 'fallback'.
Injection context
toSignal needs an injection context because it registers its cleanup with the current injector. Valid places are field initializers, constructors, and functions called from them. A regular method called later has no context, and Angular throws an error.
When you must call it elsewhere, pass an injector explicitly. The subscription then lives as long as that injector.
import { Injector, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable } from 'rxjs';
export class Loader {
private injector = inject(Injector);
start(source$: Observable<string>) {
return toSignal(source$, { injector: this.injector });
}
}Common mistakes
- Calling
toSignalinsidecomputed()oreffect(). Each run would create a new subscription. Create the signal once, then read it there. - Calling it repeatedly in a method. Each call makes a new subscription that lasts until the injector is destroyed.
- Forgetting
undefinedin the type. WithoutinitialValueorrequireSync, code that expectsTfails to compile. - Leaving errors unhandled. The failure appears at read time, far from the source.
Exercise
A component declares user = toSignal(this.http.get<User>('/api/user')). A template line reads user().name and fails to compile. Why, and what are two ways to fix it?
Show answer
Without initialValue or requireSync, the type is Signal<User | undefined>, so user() may be undefined. Fix it by guarding the read, for example user()?.name, or by passing initialValue with a placeholder User. requireSync is not suitable here because an HTTP request does not emit synchronously.