Sub topic 12
Bridging Signals and RxJS
This chapter assumes you know basic RxJS: Observables, pipe(), and operators such as debounceTime and switchMap. It also assumes you have read the earlier chapters on computed() and effect().
Signals and Observables solve different problems. A signal always holds a current value that you read synchronously. An Observable is a stream of values over time, and it is good at timing, cancellation, and async work such as HTTP calls. Angular's @angular/core/rxjs-interop package gives you two functions to move between them:
| Function | Converts | Typical use |
|---|---|---|
| `toSignal(obs$)` | Observable to signal | Read the result of a stream in a template |
| `toObservable(sig)` | Signal to Observable | Apply RxJS operators to signal changes |
The round trip: a debounced search
The most common pattern starts with a signal, passes it through RxJS operators, and turns the result back into a signal.
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-search',
template: `
<input [value]="query()" (input)="query.set($any($event.target).value)" />
@for (item of results(); track item) {
<p>{{ item }}</p>
}
`,
})
export class SearchComponent {
private http = inject(HttpClient);
query = signal('');
results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
switchMap(q => this.http.get<string[]>(`/api/search?q=${encodeURIComponent(q)}`))
),
{ initialValue: [] as string[] }
);
}toObservable emits each new value of query. debounceTime waits for the user to stop typing for 300 ms, and switchMap cancels any HTTP request that is still in flight when a new query arrives. toSignal subscribes to the final stream and stores the latest response, so the template reads results() like any other signal.
How toSignal behaves
- It subscribes immediately. The subscription starts when
toSignalis called, not when the signal is first read. - It cleans up automatically. When the component or service that created it is destroyed, Angular unsubscribes. You don't need
takeUntilorasyncpipes. - It needs an injection context. Call it in a field initializer or constructor. Outside one, pass
{ injector }explicitly. - It has an initial value. An Observable may not emit right away. Without
initialValue, the signal type isT | undefinedand starts asundefined. - It can require a synchronous first value. If the source emits synchronously on subscribe, as a
BehaviorSubjectdoes, use{ requireSync: true }to get a type withoutundefined. Angular throws if no value arrives synchronously.
import { BehaviorSubject } from 'rxjs';
import { toSignal } from '@angular/core/rxjs-interop';
// Inside an injection context, e.g. a component field:
const page$ = new BehaviorSubject(1);
const page = toSignal(page$, { requireSync: true }); // Signal<number>- It rethrows errors. If the Observable errors, reading the signal throws that error. Handle failures in the stream with
catchErrorif the template should keep working.
How toObservable behaves
toObservable uses an effect() internally, so it also needs an injection context. That has two consequences:
- It emits asynchronously, when the effect runs, not at the moment you call
set(). - Changes made in quick succession are collapsed. If you call
query.set('a')and thenquery.set('ab')in the same task, the Observable emits only'ab'.
The first emission is the signal's current value. For a search box, collapsing values is fine. If you need every intermediate value as a separate event, use a Subject instead of a signal.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| NG0203 error about injection context | `toSignal` or `toObservable` called in a method or `ngOnInit` | Move it to a field or constructor, or pass `{ injector }` |
| Template shows nothing at first | No `initialValue`, signal is `undefined` | Add `initialValue` |
| Component breaks after a failed request | Stream error rethrown on read | Add `catchError` inside `switchMap` |
| Missing intermediate values | `toObservable` collapses synchronous updates | Use a `Subject` for event streams |
Exercise
A component calls this.count.set(1); this.count.set(2); this.count.set(3); in one click handler, and toObservable(this.count) is subscribed with a logger. What does the logger print for this click, and why?
Show answer
It prints only 3. toObservable is built on an effect, which runs asynchronously after the handler finishes, so it sees only the latest value and collapses the three synchronous updates into one emission.
Exercise
You write user = toSignal(this.http.get<User>('/api/me')); and the template shows {{ user().name }}. Why does this fail on first render, and what are two ways to fix it?
Show answer
The HTTP Observable has not emitted yet, so user() is undefined and reading .name throws. Fix it by providing an initialValue (for example, a placeholder User or null with a guard), or by guarding in the template with @if (user(); as u) { {{ u.name }} }.