搜索
首页web前端js教程Pass manual injector to the toSignal function to avoid outside Context Injection error

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

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());
   });
 }
}

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[];
}
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);
     }));
 }
}

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 {}
}

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 {}

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>;
}

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>;
}

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 });
  }
}

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" />

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()));
   })
 }
}

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" />

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:

  • toSignal official documentation: https://angular.dev/guide/signals/rxjs-interop#injection-context
  • ToSignalOptions: https://angular.dev/api/core/rxjs-interop/ToSignalOptions#
  • RunInInjectionContext: https://angular.dev/api/core/rxjs-interop/ToSignalOptions#
  • GitHub Issue: https://github.com/angular/angular/issues/50947
  • Stackblitz Demo: https://stackblitz.com/edit/stackblitz-starters-xsitft?file=src%2Fstar-war.component.ts

以上是Pass manual injector to the toSignal function to avoid outside Context Injection error的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
在JavaScript中替换字符串字符在JavaScript中替换字符串字符Mar 11, 2025 am 12:07 AM

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

构建您自己的Ajax Web应用程序构建您自己的Ajax Web应用程序Mar 09, 2025 am 12:11 AM

因此,在这里,您准备好了解所有称为Ajax的东西。但是,到底是什么? AJAX一词是指用于创建动态,交互式Web内容的一系列宽松的技术。 Ajax一词,最初由Jesse J创造

如何创建和发布自己的JavaScript库?如何创建和发布自己的JavaScript库?Mar 18, 2025 pm 03:12 PM

文章讨论了创建,发布和维护JavaScript库,专注于计划,开发,测试,文档和促销策略。

如何在浏览器中优化JavaScript代码以进行性能?如何在浏览器中优化JavaScript代码以进行性能?Mar 18, 2025 pm 03:14 PM

本文讨论了在浏览器中优化JavaScript性能的策略,重点是减少执行时间并最大程度地减少对页面负载速度的影响。

如何使用浏览器开发人员工具有效调试JavaScript代码?如何使用浏览器开发人员工具有效调试JavaScript代码?Mar 18, 2025 pm 03:16 PM

本文讨论了使用浏览器开发人员工具的有效JavaScript调试,专注于设置断点,使用控制台和分析性能。

jQuery矩阵效果jQuery矩阵效果Mar 10, 2025 am 12:52 AM

将矩阵电影特效带入你的网页!这是一个基于著名电影《黑客帝国》的酷炫jQuery插件。该插件模拟了电影中经典的绿色字符特效,只需选择一张图片,插件就会将其转换为充满数字字符的矩阵风格画面。快来试试吧,非常有趣! 工作原理 插件将图片加载到画布上,读取像素和颜色值: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data 插件巧妙地读取图片的矩形区域,并利用jQuery计算每个区域的平均颜色。然后,使用

如何构建简单的jQuery滑块如何构建简单的jQuery滑块Mar 11, 2025 am 12:19 AM

本文将引导您使用jQuery库创建一个简单的图片轮播。我们将使用bxSlider库,它基于jQuery构建,并提供许多配置选项来设置轮播。 如今,图片轮播已成为网站必备功能——一图胜千言! 决定使用图片轮播后,下一个问题是如何创建它。首先,您需要收集高质量、高分辨率的图片。 接下来,您需要使用HTML和一些JavaScript代码来创建图片轮播。网络上有很多库可以帮助您以不同的方式创建轮播。我们将使用开源的bxSlider库。 bxSlider库支持响应式设计,因此使用此库构建的轮播可以适应任何

如何使用Angular上传和下载CSV文件如何使用Angular上传和下载CSV文件Mar 10, 2025 am 01:01 AM

数据集对于构建API模型和各种业务流程至关重要。这就是为什么导入和导出CSV是经常需要的功能。在本教程中,您将学习如何在Angular中下载和导入CSV文件

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器