Sub topic 11
Bridging signals and RxJS
Signals hold a current value, and RxJS observables describe values arriving over time. Real Angular apps use both: HttpClient, the router and form events produce observables, while templates and computed() work best with signals. This chapter covers the two functions that connect them, toSignal() and toObservable().
This chapter assumes you know basic RxJS (pipe, switchMap, subscriptions), writable signals, computed() and effect(), and what an injection context is.
Observable to signal with toSignal()
toSignal() subscribes to an observable and returns a read-only signal that holds the latest emitted value. Both functions live in @angular/core/rxjs-interop.
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 TickerComponent {
seconds = toSignal(interval(1000), { initialValue: 0 });
}Some details of how toSignal() behaves:
- It subscribes immediately, when it is called, not when the signal is first read.
- It unsubscribes automatically when the surrounding injection context is destroyed. In a component field initializer, that means when the component is destroyed.
- A signal must always have a value, but an observable may not have emitted yet. Without
initialValue, the signal type includesundefined. - If the observable emits synchronously on subscribe, such as a
BehaviorSubject, passrequireSync: true. The type then excludesundefined, and Angular throws if no value arrives synchronously.
The resulting signal is read-only. It has no set() or update(), so the observable stays the single source of truth. You can use it in computed() and effect() like any other signal.
Signal to observable with toObservable()
toObservable() goes the other way. It lets you apply RxJS operators such as debounceTime or switchMap to a signal's changes.
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-user-search',
template: `
<input (input)="query.set($any($event.target).value)" />
<p>{{ results().length }} results</p>
`,
})
export class UserSearchComponent {
private http = inject(HttpClient);
query = signal('');
results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
switchMap((q) => this.http.get<string[]>('/api/users', { params: { q } })),
),
{ initialValue: [] as string[] },
);
}The data flows from a signal to an observable pipeline and back to a signal. Templates only ever read signals, and RxJS does the work it is good at: timing and cancellation.
Timing differences to know about
toObservable() is built on effect(). It therefore follows effect timing, not the immediate behavior of the signal itself.
- The observable emits when the effect runs, not at the moment of
set(). - If a signal changes several times before the effect runs, only the last value is emitted. Intermediate values are lost.
- The current value is emitted to each new subscriber, similar to a
BehaviorSubject.
Common errors
Calling outside an injection context. Both functions need one, so they work in field initializers and constructors. In a method, pass an injector explicitly.
import { Component, Injector, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-lazy-ticker',
template: `<button (click)="start()">Start</button>`,
})
export class LazyTickerComponent {
private injector = inject(Injector);
start() {
const seconds = toSignal(interval(1000), {
initialValue: 0,
injector: this.injector,
});
console.log(seconds());
}
}Alternatively, use manualCleanup: true. Then you are responsible for the subscription, which stays alive until the observable completes.
Observable errors. If the source observable errors, reading the signal throws that error. Handle it with catchError before toSignal().
Creating the conversion inside a computed or effect. Each run would create a new subscription. Create the converted signal once, at the field level.
Forgetting that toSignal() subscribes eagerly. A cold observable, such as an HTTP request, starts as soon as the signal is created, even if no template reads it.
Choosing a direction
| Situation | Use |
|---|---|
| Show an observable's latest value in a template | `toSignal()` |
| Combine an observable with a `computed()` value | `toSignal()`, then `computed()` |
| Debounce or cancel work triggered by a signal | `toObservable()` with operators |
| Need every emission, including rapid ones | A `Subject`, not `toObservable()` |
Exercise
A component has term = signal(''). You want an HTTP search to fire 300 ms after the user stops typing, and to cancel the previous request when a new term arrives. Which functions and operators do you use, and why is effect() a poor fit?
Show answer
Use toObservable(this.term).pipe(debounceTime(300), switchMap(t => http.get(...))), then wrap the result in toSignal() with an initialValue so the template can read it. debounceTime handles the delay and switchMap cancels the older request. An effect can fire the request, but it has no built-in debouncing or cancellation, and writing the response back into a signal from an effect is the pattern that derived-state guidance warns against.
Exercise
What does toSignal(source$) return for its type when source$ is Observable<number> and you pass no options, and how do you remove undefined from the type if the source is a BehaviorSubject?
Show answer
The type is Signal<number | undefined>, because no value may have arrived yet. For a source that emits synchronously on subscribe, pass requireSync: true to get Signal<number>. You could also pass an initialValue.