Angular原生联邦项目路由加载远程模块时出现NgModule类型不匹配断言错误
Angular原生联邦项目路由加载远程模块时出现NgModule类型不匹配断言错误
问题诊断
从你提供的错误栈和代码来看,这个断言错误的核心原因非常明确:你在Shell(宿主)的路由配置中错误地使用了loadChildren来加载远程的独立组件App,但loadChildren的设计目标是加载包含路由配置的NgModule,而非单个独立组件。Angular在类型校验时发现实际返回的是Component类型,完全不符合预期的NgModuleType,因此抛出了这个错误。
具体来看你的代码:
- 远程项目的
app.ts是一个standalone: true的组件,并非NgModule; - Shell的
app.routes.ts中,loadChildren试图将这个独立组件作为路由模块加载,这完全违背了loadChildren的使用规则。
针对性解决方案
根据你想要实现的“让Shell连接远程所有组件/路由”的需求,我提供两种可行的解决方案:
方案一:加载单个远程独立组件(适合仅挂载单个组件的场景)
如果你的需求只是在Shell的/vehicle路径下挂载远程的根组件,那么应该将loadChildren替换为loadComponent(Angular专为加载独立组件设计的路由配置项):
修改Shell的app.routes.ts:
import { loadRemoteModule } from '@angular-architects/native-federation'; import { Routes } from '@angular/router'; import { Header } from './header/header'; // 确保导入正确的404组件 export const routes: Routes = [ { path: '', redirectTo: 'vehicle', pathMatch: 'full', }, { path: 'vehicle', loadComponent: () => loadRemoteModule('vehicle', './app').then(m => m.App) .catch(err => console.error(err)) }, // 其他路由配置 { path: '**', component: Header }, // 修正笔误:Headers -> Header ];
方案二:加载远程完整路由树(推荐,适配你挂载所有远程组件的需求)
如果需要在Shell的/vehicle路径下承接远程的所有子路由(比如/vehicle/add、/vehicle/update/:id),需要调整远程的暴露内容和Shell的路由配置:
步骤1:在远程项目中创建并暴露路由模块
在远程项目中新建一个路由模块文件vehicle-routing.module.ts,用于包裹远程的路由配置:
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { routes } from './app.routes'; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class VehicleRoutingModule { }
然后修改远程的federation.config.js,新增对这个路由模块的暴露:
module.exports = withNativeFederation({ name: 'vehicle', exposes: { './app': './projects/vehicle/src/app/app.ts', './VehicleRoutingModule': './projects/vehicle/src/app/vehicle-routing.module.ts', // 新增暴露 './routes': './projects/vehicle/src/app/app.routes.ts', './VehicleComponent': './projects/vehicle/src/app/pages/vehicle/vehicle.component.ts', './AddVehicleComponent': './projects/vehicle/src/app/pages/addVehicle/addVehicle.component.ts', './UpdateVehicleComponent': './projects/vehicle/src/app/pages/updateVehicle/updateVehicle.component.ts' }, // 其余配置保持不变 });
步骤2:修改Shell的路由配置加载远程路由模块
调整Shell的app.routes.ts,使用loadChildren加载远程的路由模块:
import { loadRemoteModule } from '@angular-architects/native-federation'; import { Routes } from '@angular/router'; import { Header } from './header/header'; export const routes: Routes = [ { path: '', redirectTo: 'vehicle', pathMatch: 'full', }, { path: 'vehicle', loadChildren: () => loadRemoteModule('vehicle', './VehicleRoutingModule').then(m => m.VehicleRoutingModule) .catch(err => console.error(err)) }, // 其他路由配置 { path: '**', component: Header }, ];
额外检查点
为了避免其他潜在问题,建议你再检查以下几点:
- 共享依赖正确性:确保远程
federation.config.js中@angular/router、@angular/core等核心依赖已正确共享,避免版本冲突导致的隐藏问题; - 路由守卫的可用性:远程路由中使用了
authGuard,确保该守卫依赖已在Shell中正确共享,或者Shell项目也能访问到这个守卫; - 笔误修正:Shell路由中的
{ path: '**', component: Headers }存在笔误,应该是你导入的Header组件,否则会导致404页面找不到组件的错误。
内容来源于stack exchange
相关产品推荐
相关产品推荐

