Angular13升级至17后库组件调用报NG0203错误求助
升级Angular 13库至Angular 17后NG0203注入上下文错误解决方案
问题详情
将基于Angular 13开发的组件库升级到Angular 17版本后,在Angular 17项目中引入并使用该库时,无法正常调用库内组件或模块,抛出如下错误:
main.ts:11 ERROR Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at https://angular.io/errors/NG0203 at injectInjectorOnly (core.mjs:1093:15) at ɵɵinject (core.mjs:1106:60) at Module.ɵɵdirectiveInject (core.mjs:11047:16) at NodeInjectorFactory.DimoComponent_Factory [as factory] (dimo.component.ts:13:27) at getNodeInjectable (core.mjs:5984:44) at instantiateAllDirectives (core.mjs:11907:27) at createDirectivesInstances (core.mjs:11306:5) at ɵɵelementStart (core.mjs:23045:9) at HomeComponent_Template (template.html:5:5) at executeTemplate (core.mjs:11268:9)
库中报错的DimoComponent代码如下:
@Component({ selector: 'lib-dimo', templateUrl: './dimo.component.html', styleUrls: ['./dimo.component.scss'] }) export class DimoComponent implements OnInit { @Input() styleClass = 'mobile'; @Input() descriptionCode = ''; @Output() parentObservable: EventEmitter<any> = new EventEmitter<any>(); @Output() executionDimo: EventEmitter<boolean> = new EventEmitter<boolean>(); localFormGroup: UntypedFormGroup; dimoCaption: ICaption = {}; dimoShowStatus: IShowStatus = { status: false }; dimoAutorization: any[] = [ { label: 'SI', value: true }, { label: 'NO', value: false } ]; constructor(private _dimoLibraryService: DimoLibraryService) { this.localFormGroup = new UntypedFormGroup({ value: new UntypedFormControl(true) }); } public ngOnInit(): void { this.emitExecuteEnrollment(); this._dimoLibraryService .getDimoShowStatus() .pipe( tap(showStatus => { if (showStatus.status == true) { this.emitExecutionNull(true); this._dimoLibraryService .getDimoCaption(this.descriptionCode) .subscribe(dimoCaption => (this.dimoCaption = dimoCaption)); } else { this.emitExecutionNull(false); } }) ) .subscribe(showStatus => (this.dimoShowStatus = showStatus)); } emitExecuteEnrollment(): void { this.parentObservable.emit( this._dimoLibraryService.setDimoEnrollment( this.localFormGroup.get('value')?.value ) ); } emitExecutionNull(emitEvent: boolean): void { this.executionDimo.emit(emitEvent); } }
解决方法
在项目的angular.json配置文件中,找到对应项目的构建配置节点(路径为projects -> [项目名称] -> architect -> build -> options),添加"preserveSymlinks": true属性即可解决该注入上下文错误:
"build": { "builder": "@angular-devkit/build-angular:application", "options": { // 其他已有的配置项 "preserveSymlinks": true }, // 其他构建相关配置 }
内容的提问来源于stack exchange,提问作者nivmtz
相关产品推荐
相关产品推荐

