Sub topic 2
Why the interop functions need an injection context
This chapter assumes you can write an Angular component, use inject(), and read a signal. It also assumes you know what subscribe and Observable mean in RxJS. The goal is to explain why toSignal and toObservable throw an error when you call them in the wrong place, and how to fix it.
The error you will see
Run this component and Angular throws an error. In development the message is NG0203: toSignal() can only be used within an injection context.
import { Component, OnInit } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-broken',
template: `<p>{{ seconds() }}</p>`,
})
export class Broken implements OnInit {
seconds!: ReturnType<typeof toSignal<number>>;
ngOnInit() {
// Throws NG0203: ngOnInit is not an injection context.
this.seconds = toSignal(interval(1000));
}
}The code is valid TypeScript, and the error appears only when it runs. To fix it you need to know what an injection context is and why these functions require one.
What an injection context is
An injection context is a short window of time in which Angular knows which injector is "current". The inject() function reads that current injector. Outside the window, inject() has nothing to read and throws NG0203.
Angular opens the window in these places:
- The constructor of a component, directive, pipe or service.
- Field initializers of those classes, such as
private http = inject(HttpClient). - Factory functions passed to providers, such as
useFactory, and the functions used byInjectionTokenfactories. - Callbacks run through
runInInjectionContext(injector, fn).
It is not open in lifecycle hooks such as ngOnInit, in event handlers, in setTimeout callbacks, or inside subscribe callbacks. Those run later, after Angular has closed the window.
Why the interop functions need it
Both functions need to tie their work to a lifetime, and they get that lifetime from the injector.
toSignal subscribes to your observable straight away. If nothing ever unsubscribed, a component destroyed by the router would leave its subscription running. So toSignal looks up a DestroyRef from the current injector and registers a cleanup callback. When the component or service is destroyed, the subscription ends. The next chapters cover this in detail.
toObservable has a different need. It creates an effect to watch the signal, and effects also need an injector to know when to stop. A ReplaySubject is created inside it, and the effect is destroyed with the owning context.
In both cases the injection context is how the function finds the object whose destruction should end the subscription or effect. You do not pass a DestroyRef yourself. Angular finds it for you, but only if you call the function where it can.
Fix 1: call it where a context exists
The simplest fix is to move the call into a field initializer or constructor. That is the most common pattern.
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 Ticker {
// A field initializer runs in an injection context.
seconds = toSignal(interval(1000), { initialValue: 0 });
}Fix 2: pass an injector
Sometimes the call has to happen later, for example when the observable only exists after the user clicks a button. In that case, grab an Injector while a context is active and pass it through the injector option.
import { Component, Injector, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable, of } from 'rxjs';
@Component({
selector: 'app-lazy',
template: `
<button (click)="load()">Load</button>
<p>{{ value() }}</p>
`,
})
export class Lazy {
private injector = inject(Injector);
value = () => this.result?.();
private result?: () => string | undefined;
load() {
const source$: Observable<string> = of('loaded');
// Event handler: no context, so supply the injector.
this.result = toSignal(source$, { injector: this.injector });
}
}The subscription now lives as long as the injector you passed, which here is the component's injector. The same injector option exists on toObservable.
Fix 3: runInInjectionContext
If you have an injector and want several calls, or other inject() calls, to run together, wrap them.
import { Injector, runInInjectionContext } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable } from 'rxjs';
export function connect(injector: Injector, source$: Observable<number>) {
return runInInjectionContext(injector, () => toSignal(source$));
}Choosing an approach
| Situation | Use |
|---|---|
| Value is known at construction time | Field initializer or constructor |
| Created later, one call | `injector` option |
| Created later, several injection-dependent calls | `runInInjectionContext` |
The injector you choose decides when the subscription ends. Passing a root-level injector from a component method keeps the subscription alive after the component is destroyed. Pass the injector of the object that should own the stream.
The manualCleanup option for toSignal skips the DestroyRef lookup, so it does not need a context. Then you are responsible for ending the subscription, usually by completing the source. Do not use it just to silence the error.
Exercise
A component calls toObservable(this.filter) inside a (click) handler and throws NG0203. Give two ways to fix it.
Show answer
Move the call to a field initializer or constructor so it runs in an injection context. Or inject Injector as a field and call toObservable(this.filter, { injector: this.injector }) in the handler. Wrapping the call in runInInjectionContext(this.injector, ...) also works.