skip to content
Alvin Lucillo

Using toObservable outside DI context

/ 1 min read

When working with toObservable, you need to ensure that you use that within the injection context like constructor. This is for Angular change detection to track changes, like for memory cleanup.

Sample error:

ERROR RuntimeError: NG0203: toObservable() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at

Component:

<button class="btn" (click)="onToObservable()">toObservable</button>
  onToObservable() {
    const courses$ = toObservable(this.#courses);
    courses$.subscribe(courses => console.log('courses$', courses))
  }

To fix that, you can use the injector service to inform the Angular change detection of an observable outside the injection context.

  injector = inject(Injector)

  onToObservable() {
    const courses$ = toObservable(this.#courses, {
      injector: this.injector
    });
    courses$.subscribe(courses => console.log('courses$', courses))
  }