Sub topic 15
Bridging Observables and Signals with toSignal and toObservable
This chapter assumes you know Angular signals (signal, computed, and reading a signal by calling it). It also assumes you have read the earlier chapters on subscription lifecycle and observable-based state services. Signals hold a current value and update templates directly. Observables model events over time. The @angular/core/rxjs-interop package converts between the two, so you can use each one where it fits best.
The Working Model
toSignal subscribes to an observable and stores each emitted value in a read-only signal. toObservable watches a signal and emits its value whenever the value changes.
| Function | Input | Output | Cleanup |
|---|---|---|---|
| `toSignal` | Observable | Read-only signal | Unsubscribes when the injection context is destroyed |
| `toObservable` | Signal | Observable | The internal effect stops on destroy |
From Observable to Signal
The cart badge from the state service chapter shows the basic pattern:
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 subscription starts right away, not when the template first reads the signal. It ends when the component is destroyed, so you get the leak protection of the async pipe without the pipe.
From Signal to Observable
toObservable lets you send a signal through RxJS operators. In this example a search term stored in a signal drives a debounced HTTP request:
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, switchMap } from 'rxjs';
@Component({
selector: 'app-signal-search',
standalone: true,
template: `
<input (input)="query.set($any($event.target).value)" />
<ul>
@for (r of results(); track r) {
<li>{{ r }}</li>
}
</ul>
`,
})
export class SignalSearchComponent {
private http = inject(HttpClient);
query = signal('');
results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
switchMap(q =>
this.http.get<string[]>('/api/search', { params: { q } })
)
),
{ initialValue: [] as string[] }
);
}The time-based work stays in RxJS. The value the template reads comes back as a signal.
Common Errors
- Calling outside an injection context. Both functions need an injection context: a field initializer, a constructor, or
runInInjectionContext. If you call them inngOnInitor a click handler, Angular throws an error. Pass{ injector }explicitly if you have to call them later. - Forgetting
initialValue. If you leave it out, the signal's type includesundefined, and the signal readsundefineduntil the first emission. If the source emits synchronously, as aBehaviorSubjectdoes, use{ requireSync: true }to keep the type narrow. - Expecting every intermediate value from
toObservable.toObservableemits from an effect, so values arrive asynchronously. Severalsetcalls in the same task produce only the final value. - Swallowed errors. If the source observable errors, reading the signal throws that error. Handle failures with
catchErrorbefore you calltoSignal.
Exercise
A component calls toSignal(this.route.paramMap) inside ngOnInit and gets a runtime error. Why, and what are two fixes?
Show answer
toSignal needs an injection context, and ngOnInit does not provide one. Move the call to a field initializer or the constructor, or inject an Injector and pass it as toSignal(obs$, { injector: this.injector }).
Exercise
A signal is set to 'a', 'ab', and 'abc' in the same synchronous block. How many values does toObservable of that signal emit?
Show answer
One value, 'abc'. toObservable emits from an effect that runs after the synchronous changes, so it sees only the latest value.