Angular跨版本MFE(主19+微17)Web Component模式下NG0203错误求助
问题场景
主应用基于Angular 19,微前端基于Angular 17,采用Web Component + Module Federation实现微前端集成,运行时触发以下错误:
ERROR RuntimeError: 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
现有配置
主应用(Angular 19)Webpack.config.js
plugins: [ new ModuleFederationPlugin({ library: { type: 'module' }, remotes: { }, shared: share({ '@angular/core': { singleton: false, strictVersion: false, requiredVersion: 'auto', }, '@angular/common': { singleton: false, strictVersion: false, requiredVersion: 'auto', }, '@angular/router': { singleton: false, strictVersion: false, requiredVersion: 'auto', }, ...sharedMappings.getDescriptors(), }), }), sharedMappings.getPlugin(),
微前端应用(Angular 17)App.module.ts
export class AppModule { constructor(private injector: Injector) { } ngDoBootstrap() { const ce = createCustomElement(AppComponent, {injector: this.injector}); customElements.define('angular1-element', ce); } }
微前端应用(Angular 17)Webpack.config.js
plugins: [ new ModuleFederationPlugin({ library: { type: "module" }, name: "request", filename: "remoteEntry.js", exposes: { './Module': './src/app/request.module.ts', }, shared: share({ '@angular/core': { singleton: false, strictVersion: false, requiredVersion: 'auto', }, '@angular/common': { singleton: false, strictVersion: false, requiredVersion: 'auto', }, '@angular/router': { singleton: false, strictVersion: false, requiredVersion: 'auto', }, // '@pnc/imaging': { // singleton: true, // }, ...sharedMappings.getDescriptors(), }), }), sharedMappings.getPlugin()
解决方案
核心原因
不同Angular版本的@angular/core实例隔离(singleton: false)导致注入上下文混乱,Web Component在初始化时无法正确匹配当前Angular版本的注入环境。
修复步骤
调整共享依赖的单例模式
将主应用和微前端的@angular/core、@angular/common、@angular/router的singleton设为true,确保同一依赖只加载一个兼容实例:shared: share({ '@angular/core': { singleton: true, strictVersion: false, requiredVersion: 'auto', }, '@angular/common': { singleton: true, strictVersion: false, requiredVersion: 'auto', }, '@angular/router': { singleton: true, strictVersion: false, requiredVersion: 'auto', }, ...sharedMappings.getDescriptors(), }),注:
strictVersion: false允许跨小版本兼容,requiredVersion: 'auto'自动匹配当前项目的依赖版本。强制在注入上下文内初始化Web Component
在微前端的ngDoBootstrap中,用runInInjectionContext包裹Web Component创建逻辑,确保注入上下文正确绑定:import { runInInjectionContext } from '@angular/core'; export class AppModule { constructor(private injector: Injector) { } ngDoBootstrap() { runInInjectionContext(this.injector, () => { const ce = createCustomElement(AppComponent, {injector: this.injector}); customElements.define('angular1-element', ce); }); } }补全主应用的远程依赖配置
主应用需添加微前端的remote地址,示例:remotes: { request: 'http://localhost:3000/remoteEntry.js', },
验证方法
- 重启主应用和微前端服务
- 检查浏览器控制台是否消除NG0203错误
- 确认Web Component正常渲染且依赖注入功能可用
内容的提问来源于stack exchange,提问作者vijred

