Angular模块联邦加载组件报错TypeError: container.get/init is not a function求助
问题分析
出现TypeError: container.init is not a function和TypeError: container.get is not a function的核心原因是:直接加载未关联NgModule的Angular组件。Angular组件依赖NgModule提供的注入器(Injector)和编译上下文才能正常运行,单独暴露并加载组件会导致缺少必要的容器环境。
修复步骤
1. 修正微前端Webpack配置的语法错误
你的webpack.config.js中@angular/common/http的requiredVersion存在引号缺失问题,这会导致共享依赖解析异常:
// 错误代码 "@angular/common/http": { singleton: true, strictVersion: false, requiredVersion: auto" }, // 修正后 "@angular/common/http": { singleton: true, strictVersion: false, requiredVersion: "auto" },
2. 确保微前端组件被NgModule正确导出
在微前端的MicrofrontendModule中,必须同时声明并导出TestComponent,确保shell应用能从模块上下文获取到组件类:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TestComponent } from './test/test.component'; @NgModule({ declarations: [TestComponent], exports: [TestComponent], // 关键:导出组件供外部使用 imports: [CommonModule] }) export class MicrofrontendModule { }
3. 修改远程组件加载逻辑:先加载模块,再创建组件
不能直接加载孤立的组件,需要先加载远程NgModule,利用模块的注入器来创建组件。修改mfe-loader.service.ts:
import { loadRemoteModule } from "@angular-architects/module-federation"; import { ComponentRef, Injectable, ViewContainerRef, NgModuleRef } from "@angular/core"; @Injectable({ providedIn: 'root' }) export class MFELoaderService { public async loadMFE(viewContainerRef: ViewContainerRef) { const mfeConfig = { remoteUrl: "http://localhost:3000", entryPath: "/remoteEntry.js", remoteName: "mfe", exposedModule: "./Module", componentName: "TestComponent" }; // 1. 加载远程NgModule const remoteModule = await loadRemoteModule({ remoteEntry: `${mfeConfig.remoteUrl}${mfeConfig.entryPath}`, remoteName: mfeConfig.remoteName, exposedModule: mfeConfig.exposedModule }); // 2. 在视图容器中创建模块实例,获取模块注入器 const moduleRef: NgModuleRef<any> = viewContainerRef.createNgModule(remoteModule.MicrofrontendModule); // 3. 从模块导出中获取组件类 const TestComponent = remoteModule.TestComponent; // 4. 清空容器并使用模块注入器创建组件 viewContainerRef.clear(); const componentRef: ComponentRef<any> = viewContainerRef.createComponent(TestComponent, { injector: moduleRef.injector }); // 可选:传递输入属性给组件 // componentRef.instance.someInput = '示例值'; } }
4. 优化指令的重复加载问题(可选)
添加加载状态判断,避免ngOnChanges触发时重复加载组件:
import { Directive, Input, OnChanges, ViewContainerRef } from '@angular/core'; import { MFELoaderService } from './mfe-loader.service'; @Directive({ selector: '[appMicrofrontendLoader]' }) export class MFELoaderDirective implements OnChanges { @Input() appMFELoader!: any; private isLoaded = false; constructor( private viewContainerRef: ViewContainerRef, private loaderService: MFELoaderService ) { } async ngOnChanges(): Promise<void> { if (!this.isLoaded) { await this.loaderService.loadMFE(this.viewContainerRef); this.isLoaded = true; } } }
验证方案
- 重启微前端和shell应用
- 访问shell应用中使用该指令的页面,确认
TestComponent正常渲染且无报错
内容的提问来源于stack exchange,提问作者VIK6Galado
相关产品推荐
相关产品推荐

