Sub topic 7
Turning a signal into an observable with toObservable
This chapter assumes you can create and read signals with signal() and computed(). It also assumes you know basic RxJS (subscribe, map, switchMap) and how Angular dependency injection works.
Why convert a signal to an observable
Signals hold the current value of some state. Observables describe values arriving over time. Some jobs need time-based operators such as debounceTime, switchMap or combineLatest, and a signal has no equivalent for these. toObservable from @angular/core/rxjs-interop lets you feed a signal into an RxJS pipeline.
import { signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
const query = signal('');
const query$ = toObservable(query); // Observable<string>toObservable takes a signal and returns an Observable of the same type. Every subscriber sees the signal's value, and later values as the signal changes.
It needs an injection context
toObservable creates an effect internally. An effect must be tied to an injector so Angular can destroy it later. So you must call toObservable in an injection context, such as a field initializer, a constructor, or a function run through runInInjectionContext. Outside one, you pass an injector explicitly.
import { Injector, inject, Signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
import { Observable } from 'rxjs';
export class Watcher {
private injector = inject(Injector);
watch(source: Signal<number>): Observable<number> {
return toObservable(source, { injector: this.injector });
}
}When the injector is destroyed, the effect is destroyed and the observable completes.
When it emits
toObservable does not emit synchronously on every set. It reads the signal inside an effect, and effects run later, during change detection. Two things follow:
- The observable emits the signal's current value after the effect first runs. This is not at the moment you subscribe.
- If the signal changes several times before the effect runs, subscribers see only the latest value.
import { Component, signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-demo',
template: ``,
})
export class Demo {
n = signal(0);
constructor() {
toObservable(this.n).subscribe((v) => console.log(v));
this.n.set(1);
this.n.set(2);
// toObservable emits from an effect, so the subscriber sees only the latest value (2) when the effect runs.
}
}The console prints 2. The values 0 and 1 never reach the subscriber.
Using it in a pipeline
The usual reason to call toObservable is to apply operators and then return to a signal with toSignal.
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs';
@Component({
selector: 'app-search',
template: `
<input (input)="query.set($any($event.target).value)" />
<ul>
@for (r of results(); track r) {
<li>{{ r }}</li>
}
</ul>
`,
})
export class Search {
private http = inject(HttpClient);
query = signal('');
results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((q) => this.http.get<string[]>('/api/search', { params: { q } })),
),
{ initialValue: [] as string[] },
);
}The signal query becomes a stream. debounceTime waits for 300 ms of quiet, and switchMap cancels any request that is still in flight. toSignal turns the results back into a signal for the template. A later chapter builds this pipeline step by step.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Calling `toObservable` in a plain method | Error about a missing injection context | Pass `{ injector }` or call it in a field initializer |
| Expecting one emission per `set` | Intermediate values are skipped | Use a different design if every write matters, such as a `Subject` |
| Expecting a synchronous first value | The first emission comes after the effect runs | Do not depend on it happening inside `subscribe` |
Exercise
A component runs const s = signal('a'); toObservable(s).subscribe(console.log); s.set('b'); s.set('c'); in its constructor. What does the subscriber log, and why?
Show answer
It logs only c. toObservable reads the signal inside an effect, which runs after the constructor finishes. By then the signal holds c, so the earlier values a and b are never emitted.
Exercise
You call toObservable(this.count) inside a click handler and get an error about the injection context. How do you fix it?
Show answer
Either create the observable once in a field initializer or constructor, or pass an injector explicitly with toObservable(this.count, { injector: this.injector }), where this.injector = inject(Injector) was captured in an injection context.