Sub topic 12
Bridging Signals and RxJS
Signals and RxJS Observables both model values that change over time, but they work differently. A signal always has a current value that you read synchronously. An Observable is a stream that pushes values to subscribers, and it may have no current value at all. Angular gives you two functions in @angular/core/rxjs-interop that convert one into the other: toSignal() and toObservable().
This chapter assumes you know basic RxJS (subscribing, pipe, and operators like map, debounceTime, and switchMap), Angular dependency injection, and the signal, computed(), and effect() material from earlier chapters.
When Each Model Fits
Use signals for state: a value you need right now, such as the current user, a form field, or a cart total. Use RxJS for events and asynchronous coordination, such as debouncing keystrokes, cancelling outdated HTTP requests, retrying, or merging several sources over time.
| Concern | Signals | RxJS Observables |
|---|---|---|
| Current value | Always available via `sig()` | Not guaranteed; depends on the source |
| Push or pull | Consumers pull values when they read | Producer pushes values to subscribers |
| Timing operators | None built in | `debounceTime`, `throttleTime`, `delay`, and others |
| Cancellation | Not applicable | `switchMap`, `takeUntil`, unsubscribe |
| Template use | Call directly: `{{ count() }}` | Needs `async` pipe or conversion |
| Cleanup | Automatic through the reactive graph | Must unsubscribe (or let a helper do it) |
Most real apps use both. Keep the state as signals, drop into RxJS when you need time-based logic, and convert the result back to a signal for the template.
Converting an Observable with toSignal()
toSignal(source$) subscribes to the Observable right away and returns a read-only signal that holds the most recent emitted value. When the surrounding component or service is destroyed, Angular unsubscribes for you.
import { Component, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import { map } from 'rxjs';
@Component({
selector: 'app-product-page',
template: `<h2>Product {{ productId() ?? 'loading…' }}</h2>`,
})
export class ProductPageComponent {
private route = inject(ActivatedRoute);
productId = toSignal(
this.route.paramMap.pipe(map(params => params.get('id')))
);
}The type of productId here is Signal<string | null | undefined>. The undefined comes from toSignal itself: an Observable may not have emitted yet when the signal is first read, so the signal needs some value to return.
The initial value problem
You have three ways to handle the period before the first emission.
- Accept
undefined. This is the default, as shown above. The template has to handle the missing value. - Provide
initialValue. The signal returns this value until the Observable emits, andundefineddrops out of the type. - Use
requireSync: true. This tells Angular the Observable emits synchronously on subscribe, as aBehaviorSubjector astartWith(...)pipe does. The type isSignal<T>. If the Observable does not emit synchronously,toSignalthrows an error.
import { BehaviorSubject } from 'rxjs';
import { toSignal } from '@angular/core/rxjs-interop';
import { Component } from '@angular/core';
@Component({
selector: 'app-status',
template: `<p>Online: {{ online() }} / Items: {{ items().length }}</p>`,
})
export class StatusComponent {
private online$ = new BehaviorSubject<boolean>(true);
private items$ = new BehaviorSubject<string[]>([]);
// BehaviorSubject emits immediately, so requireSync is safe.
online = toSignal(this.online$, { requireSync: true }); // Signal<boolean>
// Equivalent effect, with an explicit fallback value.
items = toSignal(this.items$, { initialValue: [] as string[] }); // Signal<string[]>
}Pick requireSync when you know the source is synchronous, because it documents that fact and fails loudly if someone later changes the source. Pick initialValue for HTTP calls and other async sources.
Errors and completion
If the Observable errors, the signal throws that error every time it is read. In a template the error surfaces during rendering, so handle errors inside the pipe with catchError if you want a fallback value. If the Observable completes, the signal keeps returning the last value it received.
Injection context and lifetime
toSignal needs to know when to unsubscribe. It gets a DestroyRef from the current injection context, so you must call it in a field initializer, in a constructor, or inside runInInjectionContext. Calling it inside a click handler or ngOnInit throws NG0203.
If you need to create it later, pass an injector explicitly:
import { Component, Injector, inject, Signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker',
template: `<button (click)="start()">Start</button> {{ ticks?.() }}`,
})
export class TickerComponent {
private injector = inject(Injector);
ticks?: Signal<number>;
start() {
this.ticks = toSignal(interval(1000), {
initialValue: 0,
injector: this.injector,
});
}
}The manualCleanup: true option turns off automatic unsubscription. Use it only for Observables that complete on their own, otherwise you create a leak.
Converting a Signal with toObservable()
toObservable(sig) returns an Observable that emits the signal's value. Internally it creates an effect() that reads the signal and pushes the value into a ReplaySubject with a buffer of one. Two consequences follow from this design.
- It needs an injection context, just like
effect(). You can pass{ injector }when calling it elsewhere. - Emissions are asynchronous and coalesced. The effect runs during Angular's scheduled effect processing, not at the moment you call
set(). If you set a signal three times in one synchronous block, subscribers see only the final value.
import { Component, signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
@Component({ selector: 'app-coalesce', template: '' })
export class CoalesceComponent {
count = signal(0);
constructor() {
toObservable(this.count).subscribe(v => console.log('emitted', v));
this.count.set(1);
this.count.set(2);
this.count.set(3);
// Logs only "emitted 3" once effects run, never 0, 1, or 2.
}
}This is correct behavior for state, because signals represent the latest value and not a log of events. If you need every intermediate value, as with an analytics event stream, use a Subject and call next() directly.
The Round Trip: Debounced Search
The most common pattern combines both functions. A signal holds the query, RxJS applies timing and cancellation, and toSignal turns the result back into something the template can read.
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[] }
);
}debounceTime(300) waits for typing to pause. switchMap cancels the previous request when a new query arrives, so a slow response for "an" cannot overwrite the result for "angular". You cannot express either behavior with computed(), which is synchronous and has no idea of time.
Other Interop Helpers
The same package has a few more tools you will run into.
takeUntilDestroyed()completes an Observable when the currentDestroyReffires. Use it for manualsubscribe()calls in components:source$.pipe(takeUntilDestroyed()).subscribe(...). Outside an injection context, pass aDestroyRefas the argument.outputFromObservable(obs$)exposes an Observable as a component output, for code that already produces events as streams.outputToObservable(ref)converts anoutput()reference into an Observable, which helps when a parent wants to apply operators to a child's events.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `NG0203: toSignal() can only be used within an injection context` | Called in a method or lifecycle hook | Move it to a field or constructor, or pass `{ injector }` |
| Template shows nothing at first, type includes `undefined` | No initial value | Add `initialValue` or `requireSync: true` |
| `toSignal` throws about synchronous emission | `requireSync` used on an async source | Use `initialValue` instead |
| HTTP request fires repeatedly | `toSignal` created inside `computed()` or a getter | Create it once as a field; drive changes through a source signal |
| Subscriber misses intermediate values | `toObservable` coalesces synchronous updates | Use a `Subject` for event streams |
| Signal throws on every read after a failure | Source Observable errored | Handle errors with `catchError` in the pipe |
Never call toSignal inside computed() or effect(). Each re-evaluation would create a new subscription, and Angular reports an error because those reactive contexts are not allowed to create new reactive owners.
Exercises
Exercise
You write user = toSignal(this.http.get<User>('/api/me')); and the template uses {{ user().name }}. TypeScript reports an error. Why, and what are two ways to fix it?
Show answer
Without an initial value, toSignal returns Signal<User | undefined>, so user() may be undefined before the HTTP response arrives. Fix it by using optional chaining in the template ({{ user()?.name }}) or by passing an initialValue of the right shape. requireSync: true would not work, because an HTTP Observable does not emit synchronously and toSignal would throw.
Exercise
A component calls this.page.set(2); this.page.set(3); back to back, and a subscriber to toObservable(this.page) logs only 3. Is this a bug?
Show answer
No. toObservable is built on an effect, which runs later and reads the signal's current value. Synchronous updates are coalesced, so only the latest value (3) is emitted. If every value matters, model it as an event stream with a Subject.
Exercise
In the debounced search example, what would go wrong if you replaced switchMap with mergeMap?
Show answer
mergeMap keeps every in-flight request alive. If an earlier request for a shorter query finishes after a later one, its results arrive last and overwrite the newer results, so the list shows stale data. switchMap cancels the previous request when a new query arrives, which prevents this.
Exercise
Why does toSignal require an injection context, and how do you call it from a button click handler?
Show answer
It uses DestroyRef from the injection context to unsubscribe automatically when the owner is destroyed. From a click handler, inject Injector in a field and pass it as toSignal(source$, { injector: this.injector, initialValue: ... }).