Pass manual injector to the toSignal function to avoid outside Context Injection error

Connie Leung - Sep 24 - - Dev Community

Required signal input can not be used in the constructor or field initializer because the value is unavailable. To access the value, my solution is to watch the signal change in effect, make an HTTP request to the server, and set the signal's value. There are many discussions on not using the effect, and I must find other solutions to remove it.

Required signal inputs are accessible in the ngOnInit and ngOnChanges lifecycle methods. However, toSignal throws errors in them because they are outside the injection context. It can be fixed in two ways:

  • Pass the manual injector to the toSignal function
  • Execute the toSignal function in the callback function of runInInjectionContext.

Use signal input in effect (To be changed later)

import { Component, effect, inject, Injector, input, signal } from '@angular/core';
import { getPerson, Person } from './star-war.api';
import { StarWarPersonComponent } from './star-war-person.component';

@Component({
 selector: 'app-star-war',
 standalone: true,
 imports: [StarWarPersonComponent],
 template: `
     <p>Jedi Id: {{ jedi() }}</p> 
     <app-star-war-person [person]="fighter()" kind="Jedi Fighter" />`,
})
export class StarWarComponent {
 // required signal input
 jedi = input.required<number>();

 injector = inject(Injector);
 fighter = signal<Person | undefined>(undefined);

 constructor() {
  effect((OnCleanup) => {
     const sub = getPerson(this.jedi(), this.injector)
       .subscribe((result) => this.fighter.set(result));

     OnCleanup(() => sub.unsubscribe());
   });
 }
}
Enter fullscreen mode Exit fullscreen mode

The code changes are the following:

  • Create a StarWarService to call the API and return the Observable
  • The StarWarComponent implements the OnInit interface.
  • Use the inject function to inject the Injector of the component
  • In ngOnInit, call the StarWar API using the required signal input and create a signal from the Observable. To avoid the error, pass the manual injector to the toSignal function.
  • In ngOnInit, the runInInjectionContext function calls the toSignal function in the context of the injector.

Create StarWarService

export type Person = {
 name: string;
 height: string;
 mass: string;
 hair_color: string;
 skin_color: string;
 eye_color: string;
 gender: string;
 films: string[];
}
Enter fullscreen mode Exit fullscreen mode
import { HttpClient } from "@angular/common/http";
import { inject, Injectable } from "@angular/core";
import { catchError, Observable, of, tap } from "rxjs";
import { Person } from "./person.type";

const URL = 'https://swapi.dev/api/people';

@Injectable({
 providedIn: 'root'
})
export class StarWarService {
 private readonly http = inject(HttpClient);

 getData(id: number): Observable<Person | undefined> {
   return this.http.get<Person>(`${URL}/${id}`).pipe(
     tap((data) => console.log('data', data)),
     catchError((err) => {
       console.error(err);
       return of(undefined);
     }));
 }
}
Enter fullscreen mode Exit fullscreen mode

Create a StarWarService with a getData method to call the StarWar API to retrieve a person. The result is an Observable of a person or undefined.

Required Signal Input

import { Component, input } from '@angular/core';

@Component({
 selector: 'app-star-war',
 standalone: true,
 template: `
  <p>Jedi Id: {{ jedi() }}</p>
  <p>Sith Id: {{ sith() }}</p>
 `,
})
export class StarWarComponent implements OnInit {
 // required signal input
 jedi = input.required<number>();

 // required signal input
 sith = input.required<number>();

 ngOnInit(): void {}
}
Enter fullscreen mode Exit fullscreen mode

Both jedi and sith are required signal inputs; therefore, I cannot use them in the constructor or call toSignal with the service to initialize fields.

I implement the OnInit interface and access both signal inputs in the ngOnInit method.

Prepare the App Component

import { Component, VERSION } from '@angular/core';
import { StarWarComponent } from './star-war.component';

@Component({
 selector: 'app-root',
 standalone: true,
 imports: [StarWarComponent],
 template: `
   <app-star-war [jedi]="1" [sith]="4" />
   <app-star-war [jedi]="10" [sith]="44" />`,
})
export class App {}
Enter fullscreen mode Exit fullscreen mode

App component has two instances of StarWarComponent. The jedi id of the first instance is 1 and the id of the second instance is 10. The sith id of the instances are 4 and 44 respectively.

Pass manual injector to toSignal to query a jedi fighter

export class StarWarComponent implements OnInit {
 // required signal input
 jedi = input.required<number>();

 starWarService = inject(StarWarService);
 injector = inject(Injector);
 light!: Signal<Person | undefined>;
}
Enter fullscreen mode Exit fullscreen mode

In the StarWarComponent component, I inject the StarWarService and the component's injector. Moreover, I declare a light Signal to store the result returned from the toSignal function.

interface ToSignalOptions<T> {
 initialValue?: unknown;
 requireSync?: boolean;
 injector?: Injector;
 manualCleanup?: boolean;
 rejectErrors?: boolean;
 equal?: ValueEqualityFn<T>;
}
Enter fullscreen mode Exit fullscreen mode

The ToSignalOptions option has an injector property. When using the toSignal function outside the injection context, I can pass the component's injector to the option.

export class StarWarComponent implements OnInit {
 // required signal input
 jedi = input.required<number>();

 starWarService = inject(StarWarService);
 injector = inject(Injector);
 light!: Signal<Person | undefined>;

 ngOnInit(): void {
   this.light = toSignal(this.starWarService.getData(this.jedi()), { injector: this.injector });
  }
}
Enter fullscreen mode Exit fullscreen mode

In the ngOnInit method, I call the service to obtain an Observable, and use the toSignal function to create a signal. The second argument is an option with the component's injector.

<app-star-war-person [person]="light()" kind="Jedi Fighter" />
Enter fullscreen mode Exit fullscreen mode

Next, I pass the light signal to the StarWarPersonComponent component to display the details of a Jedi fighter.

runInInjectionContext executes toSignal in the component’s injector

export class StarWarComponent implements OnInit {
 // required signal input
 sith = input.required<number>();

 starWarService = inject(StarWarService);
 injector = inject(Injector);
 evil!: Signal<Person | undefined>;

 ngOnInit(): void {
   // this also works
   runInInjectionContext(this.injector, () => {
     this.evil = toSignal(this.starWarService.getData(this.sith()));
   })
 }
}
Enter fullscreen mode Exit fullscreen mode

I declare an evil Signal to store the result returned from the toSignal function. The first argument of the runInInjectionContext is the component's injector. The second argument is a callback function that executes the toSignal function and assigns the person to the evil variable.

<app-star-war-person [person]="evil()" kind="Sith Lord" />
Enter fullscreen mode Exit fullscreen mode

Next, I pass the evil signal to the StarWarPersonComponent component to display the details of the Sith Lord.

If a component has required signal inputs, I can access the values in the ngOnInit or ngOnChanges to make HTTP requests or other operations. Then, I don't need to create an effect to watch the required signals and call the backend.

Conclusions:

  • Required signal input cannot be called in the constructor because the value is unavailable at that time.
  • The required signal inputs can be used in the ngOnInit or ngOnChanges methods.
  • toSignal throws errors in the ngOnInit and ngOnChanges methods because it runs outside of the injection context
  • Pass the manual injector to the injector option of ToSignalOptions
  • Call the toSignal function in the callback function of runInInjectionContext function.

This wraps up day 33 of the ironman challenge.

References:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .