Sub topic 2
Why the interop functions need an injection context
This chapter assumes you can write an Angular component with inject(), create signals with signal() and computed(), and use basic RxJS (Observable, subscribe, map, switchMap). You don't need to know how toSignal and toObservable work yet. This chapter explains one rule that decides where you can call them: they must run in an injection context, or you must give them an injector.
The error you will meet first
Sooner or later you will write something like this:
import { Component, OnInit, Signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Subject, scan } from 'rxjs';
@Component({
selector: 'app-clicks',
template: `<button (click)="clicks$.next()">Clicks: {{ total?.() }}</button>`,
})
export class Clicks implements OnInit {
clicks$ = new Subject<void>();
total?: Signal<number>;
ngOnInit() {
// Throws NG0203: toSignal() can only be used within an injection context
this.total = toSignal(this.clicks$.pipe(scan((n) => n + 1, 0)), { initialValue: 0 });
}
}Angular throws an NG0203 error. The message says toSignal() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with runInInjectionContext. The code looks harmless, so the rule seems arbitrary at first. It isn't, and the reason shows you how to fix every case.
What an injection context is
An injection context is a stretch of synchronous code during which Angular has an active injector. While it is active, calling inject(Something) returns the dependency from that injector. Outside it, inject() throws, because Angular has no idea which injector you mean.
Angular opens an injection context in these places:
- A class constructor, for classes Angular creates (components, directives, services, pipes).
- A field initializer of such a class, because initializers run as part of construction.
- A factory function, such as
useFactoryin a provider or thefactoryof anInjectionToken. - Functions Angular runs for you in a context, such as route guards, resolvers, and
provideAppInitializercallbacks. - Any callback you pass to
runInInjectionContext(injector, fn).
Angular does not open one in lifecycle hooks (ngOnInit, ngOnChanges), template event handlers, setTimeout callbacks, RxJS subscribe callbacks, or any code after an await. The context exists only while the synchronous call that created it is on the stack.
The ngOnInit example above fails because Angular created the component earlier. By the time ngOnInit runs, the constructor has returned and the context is gone.
What the interop functions use the context for
The two functions need an injector for different reasons, but both come down to cleanup.
toSignal subscribes to your observable right away. That subscription must end when the owner (usually a component) is destroyed, or it would leak. To arrange that, toSignal asks the injector for a DestroyRef. A DestroyRef is a small object that lets you register callbacks to run when the owning injector is destroyed. toSignal registers one that unsubscribes.
toObservable has a bigger need. It creates an effect internally to watch your signal. An effect needs an injector to be created and to be destroyed with its owner. So toObservable takes the Injector itself and uses it for both.
| Function | What it takes from the context | What it does with it |
|---|---|---|
| `toSignal` | `DestroyRef` | Unsubscribes from the observable when the owner is destroyed |
| `toObservable` | `Injector` (and its `DestroyRef`) | Creates the internal effect and stops it on destroy |
Both functions treat automatic cleanup as the default, and an injection context is how they get it. If they allowed calls anywhere, you would get hidden subscriptions with no owner. Angular chose a loud error over silent leaks.
Fix 1: call it where a context exists
The simplest fix is to move the call into a field initializer or the constructor. Most interop calls belong there anyway, because the signal is part of the component's state.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Subject, scan } from 'rxjs';
@Component({
selector: 'app-clicks',
template: `<button (click)="clicks$.next()">Clicks: {{ total() }}</button>`,
})
export class Clicks {
clicks$ = new Subject<void>();
// A field initializer runs during construction, inside an injection context.
total = toSignal(this.clicks$.pipe(scan((n) => n + 1, 0)), { initialValue: 0 });
}Field order matters. total reads this.clicks$, so clicks$ must be declared above it. Initializers run top to bottom. If you reverse them, this.clicks$ is undefined when toSignal runs, and you get a different, confusing error.
The same applies to inject(). A field such as private http = inject(HttpClient) must come before any field that uses this.http.
Fix 2: pass an injector
Sometimes the call can't live in a field initializer. The source observable may only exist after the user picks something, or you are inside a helper method. In that case, capture an Injector while you still have a context, and pass it through the injector option.
import { Injector, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable } from 'rxjs';
export class Loader {
private injector = inject(Injector);
start(source$: Observable<string>) {
// Outside an injection context, pass an injector explicitly.
return toSignal(source$, { injector: this.injector });
}
}toObservable accepts the same option:
import { Injector, Signal, inject } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
export class Watcher {
private injector = inject(Injector);
watch(value: Signal<number>) {
return toObservable(value, { injector: this.injector });
}
}When you pass an injector, the subscription or effect lives as long as that injector. Which injector you capture decides the lifetime:
- In a component,
inject(Injector)gives the component's own injector. It is destroyed with the component, which is usually what you want. - In a service provided in
root, it gives the root injector. That is destroyed only when the application shuts down.
The second case is a common source of leaks. If a root service's method calls toSignal with the root injector each time it runs, every call adds a subscription that lives until the app closes. The injector option fixes the error, but it doesn't make repeated calls safe. Call these functions once per piece of state, not once per user action.
Fix 3: runInInjectionContext
runInInjectionContext(injector, fn) runs a function inside a context built from the injector you give it. Code inside can call inject() and the interop functions without passing options.
import { Injector, inject, runInInjectionContext } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable } from 'rxjs';
export class Registry {
private injector = inject(Injector);
track(source$: Observable<number>) {
return runInInjectionContext(this.injector, () =>
toSignal(source$, { initialValue: 0 }),
);
}
}This is equivalent to passing { injector } for a single call. It is most useful when the function you run makes several context-dependent calls, for example a few inject() calls and two conversions.
The `await` trap
The context lasts only for the synchronous part of a call. An async function loses it at its first await.
import { Injector, inject, runInInjectionContext } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable } from 'rxjs';
export class Fetcher {
private injector = inject(Injector);
async prepare(source$: Observable<string>) {
await Promise.resolve();
// Without runInInjectionContext (or the injector option) this would throw NG0203,
// because the context ended at the await above.
return runInInjectionContext(this.injector, () =>
toSignal(source$, { initialValue: '' }),
);
}
}Capture the injector first, as a field or at the top of the function, and use it after the await. The same applies inside subscribe callbacks, setTimeout, and promise then handlers.
Option: manualCleanup for toSignal
toSignal has one option that removes the need for a context: manualCleanup: true. With it, toSignal does not register an unsubscription, so it needs no DestroyRef.
import { toSignal } from '@angular/core/rxjs-interop';
import { of } from 'rxjs';
// Allowed anywhere, because nothing will be cleaned up automatically.
const answer = toSignal(of(42), { manualCleanup: true });
console.log(answer()); // 42The subscription now lasts until the observable completes or errors. If the source never completes, such as interval(1000) or a long-lived Subject, the subscription keeps running after the component is gone. Use manualCleanup only for sources that complete on their own. The next chapters cover its lifecycle details. toObservable has no equivalent, because it always creates an effect.
A second restriction: reactive contexts
Injection contexts are not the only place toSignal can fail. Angular also forbids calling it inside a reactive context, meaning the body of a computed() or an effect(). There, the function throws a different error (NG0600).
The reason is that toSignal creates a subscription as a side effect. A computed can re-run many times, and each run would open a new subscription. Create the signal once, outside, and read it inside the computed or effect:
import { Component, computed } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { timer } from 'rxjs';
@Component({
selector: 'app-elapsed',
template: `<p>{{ label() }}</p>`,
})
export class Elapsed {
private seconds = toSignal(timer(0, 1000), { initialValue: 0 });
// Read the signal inside computed. Never call toSignal inside it.
label = computed(() => `Elapsed: ${this.seconds()}s`);
}Quick reference: where each call works
| Where you call `toSignal` or `toObservable` | Works without options? | What to do otherwise |
|---|---|---|
| Field initializer | Yes | Nothing |
| Constructor | Yes | Nothing |
| Provider factory or `InjectionToken` factory | Yes | Nothing |
| Route guard or resolver function | Yes | Nothing |
| `ngOnInit` or other lifecycle hook | No | Move to a field, or pass `injector` |
| Event handler or service method | No | Pass `injector`, or use `runInInjectionContext` |
| After an `await` or inside `subscribe` | No | Capture the injector earlier and pass it |
| Inside `computed` or `effect` | No (separate NG0600 error) | Create the signal outside and read it inside |
Tests need a context too
Unit tests run outside Angular's creation machinery, so a bare call to toSignal in a test body throws the same NG0203. Wrap the call in TestBed.runInInjectionContext(() => ...), or create the component through TestBed so its field initializers run normally. A later chapter covers testing in detail.
Summary
- An injection context is the synchronous span in which Angular has an active injector. Constructors, field initializers, factories, and
runInInjectionContextcallbacks provide one. toSignalneeds aDestroyRefto unsubscribe.toObservableneeds anInjectorto create and destroy its internal effect.- You can fix NG0203 by moving the call into a field initializer, passing
{ injector }, or wrapping the call inrunInInjectionContext. - An injector's lifetime sets the subscription's lifetime. Passing a root injector to a per-action call creates leaks.
manualCleanup: trueskips the context requirement fortoSignalbut leaves you responsible for ending the subscription.
Exercise
A service provided in root has a method watchUser(id: number). Each call runs toSignal(this.http.get<User>('/api/users/' + id), { injector: this.injector }), where this.injector = inject(Injector) was captured in a field. The code compiles and no NG0203 error appears. Name the remaining problem and give one way to fix it.
Show answer
The captured injector is the root injector, which lives until the application closes. Every call to watchUser creates a subscription and a signal that is never cleaned up before then, so repeated calls leak. Fixes: return the observable and let the calling component convert it with toSignal in its own field initializer (so the component's injector owns it), or keep one signal driven by an id signal and switchMap instead of creating a new conversion per call. For a one-shot HTTP request, which completes on its own, manualCleanup: true or simply using the observable is also acceptable.
Exercise
Why does toSignal(source$) work in a field initializer but throw NG0203 in ngOnInit, even though both belong to the same component?
Show answer
Field initializers run during construction, while Angular has an active injection context for the component's injector. ngOnInit is called later by the framework, after construction has finished, and Angular does not set up an injection context for lifecycle hooks. toSignal therefore has no DestroyRef to register its unsubscription with, so it throws.