Sub topic 15
Bridging Observables and Signals with toSignal and toObservable
Angular now has two reactive primitives. Observables model events and async work over time. Signals model current values that the template reads synchronously. Most real applications use both: HttpClient, the router, and reactive forms produce observables, and newer component code often prefers signals. The @angular/core/rxjs-interop package gives you the two functions that convert between them, toSignal and toObservable.
This chapter assumes you know how subscriptions and teardown work, how BehaviorSubject-based state services expose observables, and the basics of Angular signals (signal, computed, effect). It also assumes you know what an injection context is: the place where inject() is allowed to run.
The Mental Model: Push Streams vs Pull Values
An observable pushes values to subscribers whenever the producer decides. It has no "current value" unless it is backed by something like a BehaviorSubject. A signal always has a current value, and readers pull that value when they need it. Angular tracks which signals a template or computed reads and re-runs them when those signals change.
Converting between the two means solving two mismatches:
- Observable to signal: someone has to subscribe, and the signal needs a value before the first emission arrives.
- Signal to observable: someone has to watch the signal, and a signal can change several times before anyone looks at it.
toSignal: Reading an Observable as a Signal
toSignal(source$) subscribes to source$ right away and returns a read-only signal that holds the latest emitted value. When the surrounding injection context is destroyed, it unsubscribes. In a component, that happens when the component is destroyed. You get the same leak protection as the async pipe, and you can use the value in computed and in TypeScript code as well as in the template.
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { CartService } from './cart.service';
@Component({
selector: 'app-cart-badge',
standalone: true,
template: `<span>Cart: {{ count() }}</span>`,
})
export class CartBadgeComponent {
private cart = inject(CartService);
count = toSignal(this.cart.count$, { initialValue: 0 });
}The initial value problem
A signal must return something the moment it is read. If the observable has not emitted yet, toSignal needs a fallback. You have three options, and each one changes the resulting type:
| Call | Signal type | Value before first emission | Column |
|---|---|---|---|
| `toSignal(obs$)` | `Signal<T \ | undefined>` | `undefined` |
| `toSignal(obs$, { initialValue: x })` | `Signal<T \ | typeof x>` | `x` |
| `toSignal(obs$, { requireSync: true })` | `Signal<T>` | Throws if `obs$` did not emit synchronously |
Use requireSync: true when you know the source emits during subscription. Examples are streams derived from a BehaviorSubject, or streams that start with startWith. The count$ stream in CartService qualifies, because it maps over a BehaviorSubject:
count = toSignal(this.cart.count$, { requireSync: true }); // Signal<number>If you use requireSync on an HTTP observable, Angular throws as soon as toSignal runs, because the HTTP response cannot arrive synchronously. That failure happens immediately and is easy to spot. A wrong initialValue is quieter. Your template may render an empty list that looks like "no data", when the data is really still loading.
Errors and completion
Completion is harmless. The signal keeps the last value it received. Errors work differently: when the source errors, the next read of the signal throws that error. A template that reads the signal will then fail to render. Handle errors inside the pipe, before toSignal:
users = toSignal(
this.http.get<User[]>('/api/users').pipe(catchError(() => of([] as User[]))),
{ initialValue: [] as User[] }
);Injection context and lifetime
toSignal registers its cleanup with DestroyRef, so it must run in an injection context. Field initializers and the constructor work. ngOnInit does not work, and Angular throws NG0203 there. If you really need to create the signal later, pass an injector:
import { Component, Injector, OnInit, Signal, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { CartService } from './cart.service';
@Component({
selector: 'app-late-badge',
standalone: true,
template: `<span>{{ count?.() }}</span>`,
})
export class LateBadgeComponent implements OnInit {
private injector = inject(Injector);
private cart = inject(CartService);
count?: Signal<number>;
ngOnInit(): void {
this.count = toSignal(this.cart.count$, {
initialValue: 0,
injector: this.injector,
});
}
}The manualCleanup: true option turns off automatic unsubscription. The subscription then lasts until the source completes. Use it only for sources that are guaranteed to complete. A toSignal call inside a root service lives as long as the application does, which is usually what you want for app-wide state.
toObservable: Watching a Signal as a Stream
toObservable(sig) returns an observable that emits the signal's value whenever it changes. You need it when signal-held state must go through time-based or async RxJS operators, such as debounceTime, switchMap, or retry. Signals have no equivalents for these.
Internally, toObservable creates an effect that reads the signal and pushes each value into a ReplaySubject with a buffer of 1. That design has three consequences:
- It needs an injection context, or an
injectoroption, because effects do. - The first emission is asynchronous. Subscribing does not emit synchronously. The value arrives when the effect first runs.
- Changes are coalesced. Effects run after the current synchronous work has finished, so if you set a signal to 1, 2, and 3 in one synchronous block, subscribers see only 3.
Coalescing is usually what you want for UI state. It is the wrong tool when every value counts, for example an event log or a queue of commands. Model those as observables or Subjects from the start, and don't route them through a signal.
Round-Tripping: Signal In, Signal Out
The most common pattern combines both functions. The component keeps its input state in a signal, converts it to an observable for the async part, and converts the result back to a signal for the template:
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, debounceTime, distinctUntilChanged, of, switchMap } from 'rxjs';
@Component({
selector: 'app-user-search',
standalone: true,
template: `
<input [value]="term()" (input)="term.set($any($event.target).value)" />
<ul>
@for (name of results(); track name) {
<li>{{ name }}</li>
}
</ul>
`,
})
export class UserSearchComponent {
private http = inject(HttpClient);
term = signal('');
results = toSignal(
toObservable(this.term).pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap(t =>
t.length < 2
? of([] as string[])
: this.http
.get<string[]>('/api/search', { params: { q: t } })
.pipe(catchError(() => of([] as string[])))
)
),
{ initialValue: [] as string[] }
);
}catchError sits inside switchMap, on the inner HTTP observable. If one request fails, it becomes an empty list and the outer stream stays alive. If catchError sat on the outer stream, the first error would end the search permanently.
Choosing Between Them
| Situation | Prefer |
|---|---|
| Value derived synchronously from other state | `computed`, no RxJS |
| Async work, cancellation, debouncing, retries | Observable pipeline |
| Template needs the result of a stream | `toSignal` (or the async pipe) |
| Signal state must feed an RxJS operator | `toObservable` |
| Every intermediate value matters | Stay in observables or Subjects |
Don't convert back and forth just because you can. Each conversion adds a subscription or an effect, and toObservable adds an async hop. Pick the primitive that fits the work, and convert at the boundary between the two.
Exercise
A component declares user = toSignal(this.http.get<User>('/api/me'), { requireSync: true });. What happens, and how would you fix it?
Show answer
Angular throws an error as soon as toSignal runs, because an HTTP observable never emits synchronously during subscription. Drop requireSync and either accept a Signal<User | undefined> (and check for undefined in the template) or supply an initialValue that is a meaningful placeholder.
Exercise
You write const n = signal(0); toObservable(n).subscribe(console.log); n.set(1); n.set(2); inside a component constructor. What gets logged?
Show answer
Only 2, and only after the constructor finishes. toObservable emits from an effect, so the first emission is asynchronous and the synchronous writes 0 → 1 → 2 are coalesced. The effect reads only the latest value.
Exercise
Why does moving toSignal(this.cart.count$) from a field initializer into ngOnInit break, and what are two ways to fix it?
Show answer
toSignal needs an injection context to get a DestroyRef for cleanup, and ngOnInit is not an injection context, so Angular throws NG0203. You can move the call back to a field initializer or the constructor, or you can inject Injector in a field and pass it as the injector option.