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中文网其他相关文章!

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

JavaScript框架的强大之处在于简化开发、提升用户体验和应用性能。选择框架时应考虑:1.项目规模和复杂度,2.团队经验,3.生态系统和社区支持。

引言我知道你可能会觉得奇怪,JavaScript、C 和浏览器之间到底有什么关系?它们之间看似毫无关联,但实际上,它们在现代网络开发中扮演着非常重要的角色。今天我们就来深入探讨一下这三者之间的紧密联系。通过这篇文章,你将了解到JavaScript如何在浏览器中运行,C 在浏览器引擎中的作用,以及它们如何共同推动网页的渲染和交互。JavaScript与浏览器的关系我们都知道,JavaScript是前端开发的核心语言,它直接在浏览器中运行,让网页变得生动有趣。你是否曾经想过,为什么JavaScr


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),