Sub topic 3
Turning an observable into a signal with toSignal
This chapter assumes you can build an Angular component and inject services. It also assumes you can create and read signals with signal() and computed(), and that you know basic RxJS (Observable, subscribe, map, switchMap) and TypeScript generics. The previous chapters explained when to prefer a signal or an observable and why the interop functions need an injection context. This chapter uses both ideas without re-deriving them.
What toSignal does
toSignal lives in @angular/core/rxjs-interop. It takes an observable, subscribes to it, and returns a read-only signal. The signal always holds the latest value the observable emitted.
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 {
// Signal<number>: initialValue removes undefined from the type.
seconds = toSignal(interval(1000), { initialValue: 0 });
}Four properties of this function explain most of its behavior:
- It subscribes immediately. The subscription starts when you call
toSignal, not when something first reads the signal. A cold observable such as an HTTP request fires right away, even if no template ever reads the result. - It makes one subscription per call. Reading the signal a hundred times does not subscribe a hundred times. Calling
toSignaltwice on the same cold observable does run it twice. - The result is read-only. The returned type is
Signal<T>, notWritableSignal<T>. You cannot callsetorupdateon it. The observable is the only source of values. - It cleans up after itself. By default the subscription ends when the surrounding component, directive or service is destroyed.
The following diagram shows the sequence for the ticker above.
The return type and the undefined problem
An observable may not emit anything for a while, but a signal must always have a value. toSignal has to decide what the signal holds before the first emission. Without options, it holds undefined, and the type reflects that:
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable } from 'rxjs';
declare const source$: Observable<string>;
// Type: Signal<string | undefined>
const value = toSignal(source$);The | undefined spreads through your code. Every consumer must handle it, for example value()?.length or a template guard. There are two ways to remove it, and they suit different sources.
initialValue: supply a placeholder
initialValue sets what the signal holds until the observable emits. Use it when the source emits asynchronously, such as a timer, an HTTP call or a WebSocket.
const seconds = toSignal(interval(1000), { initialValue: 0 });
// Signal<number>The initial value can be any type that makes sense for the signal, including null:
const user = toSignal(user$, { initialValue: null });
// Signal<User | null>Using null is often better than leaving undefined in place. It states that "no value yet" is a deliberate state, and it forces consumers to handle it.
Choose the placeholder carefully. An initialValue of [] for a list is indistinguishable from a real empty response. If the UI needs to show a loading state, use a value that can represent loading, such as null, or a status object.
requireSync: assert that a value is already there
Some observables emit synchronously the moment you subscribe. BehaviorSubject and ReplaySubject with buffered values do this, as do of(...) and any startWith(...) pipeline. For these, the signal never needs a placeholder. requireSync: true tells toSignal to expect a synchronous emission and to type the signal without undefined.
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);
// Signal<number>: requireSync is valid because BehaviorSubject emits synchronously on subscribe.
count = toSignal(this.count$, { requireSync: true });
}If the observable does not emit synchronously, toSignal throws an error at the moment you call it. This is a deliberate design choice. The failure is loud and early instead of a signal that silently holds nothing. The check is a runtime check on a promise you make, so it is only as good as your knowledge of the source.
Two rules follow from this:
- You cannot pass
initialValueandrequireSynctogether. The types reject it, because the two options answer the same question in different ways. - If an observable "usually" emits synchronously, such as a service that sometimes serves a cached value, do not use
requireSync. UseinitialValue.
| Situation | Option | Resulting type | Column |
|---|---|---|---|
| Source emits later (timer, HTTP, socket) | `initialValue: x` | `Signal<T>` (or `Signal<T \ | X>`) |
| Source always emits on subscribe (`BehaviorSubject`, `startWith`) | `requireSync: true` | `Signal<T>` | |
| You want to handle "not yet" at each read | neither | `Signal<T \ | undefined>` |
Where you can call toSignal
toSignal needs an injection context because it injects DestroyRef to register its automatic cleanup. Valid places include field initializers in a component, directive or service, the constructor, and factory functions that Angular runs in an injection context.
Calling it in an ordinary method fails, because by then no injection context is active. Angular throws a NG0203 error saying an injection function was called outside an injection context. There are two fixes. The first is to capture an Injector earlier and pass it with the injector option.
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>) {
// Outside an injection context, pass an injector explicitly.
return toSignal(source$, { injector: this.injector });
}
}The subscription then lasts as long as that injector. If the injector belongs to a long-lived service, the subscription lives as long as the service, so a method that you call repeatedly leaks one subscription per call.
The second fix is to restructure the code so that toSignal runs once, in a field initializer, on an observable that already reacts to whatever the method would have changed.
toSignal also cannot be called inside a reactive context such as a computed() or effect() callback. A reactive context would re-run the callback and create a new subscription each time. Create the signal outside and read it inside.
Errors and completion
Two things can end an observable, and toSignal treats them differently.
Completion. When the observable completes, the signal keeps its last value and stays readable. A signal made from http.get(...) holds the response forever after the request finishes. Nothing special is needed.
Errors. When the observable errors, the signal does not hold the error as a value. Instead, reading the signal throws the error. In a template, that read happens during change detection, so the error reaches Angular's ErrorHandler and can break rendering of that view. Handle failures in the pipe before they reach toSignal:
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable, catchError, of } from 'rxjs';
export function safeSignal(source$: Observable<string>) {
// Must run in an injection context, for example in a field initializer or constructor.
return toSignal(
source$.pipe(catchError(() => of('fallback'))),
{ initialValue: 'loading' },
);
}catchError turns the failure into a value, so the signal stays readable. If you need to show the error in the UI, map it to a value that carries the failure, for example { status: 'error' }, rather than a bare fallback string. Later chapters return to error handling in more depth.
Automatic unsubscription and manualCleanup
By default toSignal registers a callback with the DestroyRef of the current injection context. When the component or service is destroyed, the subscription ends. You do not need takeUntilDestroyed(), ngOnDestroy, or a Subscription field for this.
Two consequences matter in practice:
- A signal created in a component stops updating when that component is destroyed. Reading it later returns the last value.
- A signal created in a root-provided service lives for the whole application, along with its subscription.
The manualCleanup: true option turns off the automatic unsubscription. The subscription then ends only when the observable completes. Use it when you want the signal to outlive its context, or when the observable is guaranteed to complete by itself.
import { toSignal } from '@angular/core/rxjs-interop';
import { of } from 'rxjs';
// No injection context needed: manualCleanup skips the DestroyRef lookup.
const answer = toSignal(of(42), { manualCleanup: true });
console.log(answer()); // 42Because nothing ends the subscription for you, manualCleanup with a never-completing source such as interval leaks. Only use it with sources that complete or that you control.
A worked comparison: toSignal versus the async pipe
Many templates already use observable$ | async. Here is the same view both ways.
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toSignal } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-tags',
template: `
@for (tag of tags(); track tag) {
<span>{{ tag }}</span>
}
`,
})
export class Tags {
private http = inject(HttpClient);
tags = toSignal(this.http.get<string[]>('/api/tags'), {
initialValue: [] as string[],
});
}The signal version has a few advantages over async:
- You can read the value in TypeScript code, not only in the template, for example inside a
computed(). - The value is available without a template subscription, so several template bindings read one subscription instead of needing
shareReplay. - Change detection can use the signal's notification, which fits zoneless and
OnPushsetups.
One difference is easy to miss. The async pipe subscribes when the template is rendered, and a view hidden by @if never subscribes. toSignal subscribes at creation. If the data is only needed behind a condition, toSignal still makes the request up front.
Common mistakes
- Calling toSignal in a method or callback. This causes
NG0203. Move it to a field initializer, or passinjector. - Calling toSignal in a getter or in
computed(). Each evaluation can create a new subscription. Create it once as a field. - Using
requireSyncon an asynchronous source. It throws immediately on creation. Switch toinitialValue. - Ignoring errors. An unhandled observable error becomes a throw on every read. Add
catchErrorupstream. - Expecting to write to the result. The returned signal is read-only. If you need a writable signal that also follows a stream, keep a
signal()and update it from asubscribe, or restructure so the stream is the single source of truth. - Forgetting that a cold source starts at once. Do not create a
toSignalfor an expensive request you may never display.
Exercise
A component has the field data = toSignal(this.service.load$()), where load$() returns an HTTP observable that emits one Item[] and then completes. (a) What is the type of data? (b) Change the call so the type is Signal<Item[]>. (c) The request fails with a 500 error. What happens when the template reads data(), and how do you prevent it?
Show answer
(a) Signal<Item[] | undefined>, because the HTTP call emits asynchronously and no initial value is given. (b) Add an initial value: toSignal(this.service.load$(), { initialValue: [] }). requireSync would be wrong here because the HTTP observable does not emit synchronously and would throw on creation. (c) Reading data() throws the HTTP error, which goes to the ErrorHandler. Prevent it by handling the error in the pipe, for example this.service.load$().pipe(catchError(() => of([] as Item[]))).
Exercise
You write start(s$: Observable<number>) { return toSignal(s$); } in a service method and get an injection context error. Name two ways to fix it and one risk of each.
Show answer
Option one is to inject an Injector in a field and pass it with toSignal(s$, { injector: this.injector }). The risk is that the subscription lasts as long as that injector, so calling start repeatedly in a long-lived service creates a new subscription each time. Option two is to move the toSignal call into a field initializer or constructor, so it runs once in an injection context. The risk is that the subscription starts at creation, so the source must already react to the changes that the method used to pass in.