Sub topic 10
Common pitfalls and when not to convert
This chapter assumes you can build components with dependency injection and use signal() and computed(). It also assumes you know basic RxJS (map, switchMap, catchError) and have met toSignal and toObservable in the earlier chapters. Here you will learn the mistakes that cause most interop bugs, how to fix each one, and how to decide when a conversion should not happen at all.
Pitfall 1: calling toSignal outside an injection context
toSignal and toObservable register cleanup with the current injector. They can only run where Angular can supply one: field initializers, constructors, factory functions, and code run through runInInjectionContext. A click handler or a plain method is not such a place. Calling them there throws error NG0203.
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toSignal } from '@angular/core/rxjs-interop';
interface User {
name: string;
}
@Component({
selector: 'app-user-bad',
template: `<button (click)="load('42')">Load</button>`,
})
export class UserBad {
private http = inject(HttpClient);
load(id: string) {
// Throws NG0203: not in an injection context.
const user = toSignal(this.http.get<User>(`/api/users/${id}`));
console.log(user());
}
}There are two fixes. The first is to pass an injector option, which also ties the subscription's lifetime to that injector. The second, usually better, is to avoid creating signals on demand. Hold the changing input in a signal and build the pipeline once, as in the search example in the earlier chapter.
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { switchMap, filter } from 'rxjs';
interface User {
name: string;
}
@Component({
selector: 'app-user',
template: `
<button (click)="userId.set('42')">Load</button>
<p>{{ user()?.name }}</p>
`,
})
export class UserView {
private http = inject(HttpClient);
userId = signal<string | null>(null);
user = toSignal(
toObservable(this.userId).pipe(
filter((id): id is string => id !== null),
switchMap((id) => this.http.get<User>(`/api/users/${id}`)),
),
);
}The pipeline is created once, in a field initializer. Each click only sets a signal.
Pitfall 2: creating a conversion on every read
A getter or method that calls toSignal creates a new subscription each time it runs. A template calls it on every change detection pass, so you get one of two outcomes. If no injection context exists, it throws. If one does exist, you leak a subscription per call and may fire a new HTTP request each time.
// Wrong: a new subscription each time the template reads `items`.
get items() {
return toSignal(this.items$, { initialValue: [] });
}
// Right: one subscription, created when the component is built.
items = toSignal(this.items$, { initialValue: [] });The same rule applies inside computed() and effect(). Recent Angular versions throw if toSignal runs in a reactive context, because each re-run would create another subscription. Create conversions at the top level of the class and read the resulting signal inside reactive code.
Pitfall 3: a signal type that includes undefined
Without initialValue or requireSync, toSignal returns Signal<T | undefined>. The signal holds undefined until the observable emits. This is correct, because nothing has arrived yet. It also forces ?. or non-null assertions through the template.
| Situation | Option | Resulting type | Column |
|---|---|---|---|
| Source emits later (HTTP, `interval`) and a placeholder is fine | `initialValue: x` | `Signal<T>` | |
| Source emits synchronously on subscribe (`BehaviorSubject`, `of`, `startWith`) | `requireSync: true` | `Signal<T>` | |
| "Not loaded" is a real state you want to show | neither | `Signal<T \ | undefined>` |
Two mistakes are common. The first is using initialValue: [] when "still loading" and "loaded, empty" need different UI. The signal cannot tell them apart, so keep undefined in that case. The second is using requireSync on an observable that is not synchronous. toSignal throws an error as soon as it subscribes and sees no immediate value. If you need a synchronous source, adding startWith(x) makes requireSync valid.
Pitfall 4: errors that surface on read
If the source observable errors, toSignal stores the error. The next time you read the signal, it throws that error. In a template, this breaks rendering. A try/catch around the read is a poor remedy. Handle errors in the stream, and decide where catchError goes.
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, of, switchMap } from 'rxjs';
@Component({
selector: 'app-lookup',
template: `<p>{{ result() }}</p>`,
})
export class Lookup {
private http = inject(HttpClient);
term = signal('angular');
result = toSignal(
toObservable(this.term).pipe(
switchMap((t) =>
this.http
.get<string>('/api/lookup', { params: { t } })
// Inside switchMap: only this request is replaced by the fallback.
.pipe(catchError(() => of('lookup failed'))),
),
),
{ initialValue: 'loading' },
);
}Placing catchError after switchMap, on the outer pipe, still stops the signal from throwing. However, the error ends the outer stream, so later changes to term never trigger another request. Placing it on the inner observable keeps the pipeline alive.
Completion is gentler. When the source completes, the signal keeps its last value and no error occurs. A signal fed by of(1, 2, 3) ends at 3. If you expected a completed stream to reset the signal, it will not.
Pitfall 5: subscriptions that outlive their purpose
By default toSignal unsubscribes when the injector is destroyed. In a component, that means when the component is destroyed. This is the right behavior almost always, but two cases need thought:
- Long-lived owners. If you call
toSignalinside a root-provided service, the subscription lasts as long as the application. For a stream such as a WebSocket, that may be what you want. For one that should stop when no one is using it, it is a leak. manualCleanup: true. This option skips the automatic unsubscribe. The subscription then ends only when the source completes. Use it for sources that complete on their own, such as a single HTTP request, or when you manage the lifetime yourself. If the source never completes and you setmanualCleanup, nothing will ever unsubscribe it.
Also remember that toSignal subscribes eagerly, at creation. A cold observable such as http.get sends its request immediately, even if no template ever reads the signal. If a request should wait until needed, do not convert it yet.
Pitfall 6: expecting toObservable to be synchronous
toObservable reads the signal inside an effect, so emissions happen when effects run, not at the moment of set. Two consequences follow.
- Intermediate values are skipped. Setting a signal to 1 and then 2 in the same tick delivers only 2.
- Equal values do not emit. Signals ignore a
setto an equal value, so no notification occurs.
This is usually a feature. It means a burst of updates triggers a single downstream request. It becomes a bug when you treat the observable as an event log, for example counting how many times a signal was set. Signals model current state, not history. If each event matters, use a Subject for the events.
A second timing issue appears in tests. Code that sets a signal and immediately asserts on the converted output sees stale data until effects have flushed. Flush them explicitly, for instance with TestBed.tick() in recent versions, before asserting. The testing chapter covers this in detail.
Pitfall 7: reading signals inside operators
toObservable tracks only the signal you pass to it. A signal read inside a switchMap callback is an ordinary read at that moment. It is not tracked, so changing it does not re-run the pipeline.
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { switchMap } from 'rxjs';
@Component({
selector: 'app-paged-bad',
template: `<button (click)="page.set(page() + 1)">Next</button>`,
})
export class PagedBad {
private http = inject(HttpClient);
query = signal('');
page = signal(1);
results = toSignal(
toObservable(this.query).pipe(
// page() is read here but not tracked: changing page does not refetch.
switchMap((q) =>
this.http.get<string[]>('/api/items', {
params: { q, page: this.page() },
}),
),
),
{ initialValue: [] as string[] },
);
}The fix is to merge the inputs into one signal with computed, then convert that.
import { Component, computed, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { switchMap } from 'rxjs';
@Component({
selector: 'app-paged',
template: `<button (click)="page.set(page() + 1)">Next</button>`,
})
export class Paged {
private http = inject(HttpClient);
query = signal('');
page = signal(1);
private params = computed(() => ({ q: this.query(), page: this.page() }));
results = toSignal(
toObservable(this.params).pipe(
switchMap(({ q, page }) =>
this.http.get<string[]>('/api/items', { params: { q, page } }),
),
),
{ initialValue: [] as string[] },
);
}Combining signals first is also better than converting each one and joining them with combineLatest. Each conversion emits on its own effect schedule, which can produce a mismatched pair for a moment. A single computed signal changes atomically.
Pitfall 8: writing signals from subscribers and creating loops
Calling someSignal.set(...) inside a subscribe callback on a stream derived from that same signal produces an update loop. Even without a loop, it hides data flow. Prefer one direction: signals into a stream, the stream into toSignal, the result read by the template. Avoid pushing values back with set from the middle.
When not to convert
Conversion adds a subscription, a timing difference, and a second mental model. Before you convert, check whether you need it.
A few concrete cases:
- Derived values.
fullName = computed(() => first() + ' ' + last())needs no RxJS. Going throughtoObservable,map, andtoSignalgives you the same result with delay and extra code. - Event streams. Clicks, websocket messages, and form submissions are events. A signal keeps only the latest, so intermediate events vanish. Keep them as observables and convert only the state you show.
- Existing observable-heavy code. If a service exposes observables and its consumers use
asyncpipe orsubscribecorrectly, converting everything to signals gains little. Convert at the edge where a template orcomputedneeds the value. - One-shot requests. A single request triggered by a signal change is a good fit for the pipeline above. A request with no reactive input needs only
toSignal(http.get(...)), or a plainsubscribe.
Angular also offers resource APIs for signal-driven async loading. Their stability varies by version, so check the documentation for yours before replacing a working pipeline.
Quick checklist
- Is every
toSignalandtoObservablecall in an injection context, or given aninjector? - Is each conversion created once, not in a getter, method,
computed, oreffect? - Does the signal type match what the UI needs:
initialValue,requireSync, or an honestundefined? - Does
catchErrorsit on the inner observable if the pipeline must survive errors? - Are all inputs to the pipeline merged into the signal passed to
toObservable? - Does your code depend on seeing every signal change? If so, signals are the wrong tool.
Exercise
A component has page = signal(1) and sort = signal('name'). It builds results = toSignal(toObservable(this.page).pipe(switchMap((p) => this.http.get('/api/items', { params: { p, s: this.sort() } }))), { initialValue: [] }). Users report that changing the sort order does nothing until they change the page. Explain why and give the fix.
Show answer
toObservable tracks only page. The call this.sort() inside switchMap is an untracked read, so changing sort never re-runs the pipeline. Create params = computed(() => ({ p: this.page(), s: this.sort() })), pass toObservable(this.params) into the pipe, and read p and s from the emitted object in switchMap. Both inputs are then tracked through one signal.
Exercise
A search pipeline uses toObservable(query).pipe(debounceTime(300), switchMap(q => http.get(...)), catchError(() => of([]))) and passes it to toSignal. After one failed request, typing new queries never updates the results. Why, and where should catchError go?
Show answer
The catchError is on the outer stream. It replaces the error with [], and then the outer stream completes, so later query changes no longer reach switchMap. Move catchError inside the switchMap callback, attached to http.get(...). Then only the failed request is replaced by [], and the outer stream stays alive for the next query.