【发布时间】:2020-02-21 21:24:44
【问题描述】:
我需要将提供程序传递给延迟加载的模块。 语境: 我有一个模块可以访问 API 并返回一些要在组件中呈现的配置。 这是模块:
@NgModule({
declarations: [AuxTablesComponent, AuxTablesListingComponent],
providers: [AuxTablesService, AuxTableDataResolverGuard],
imports: [CommonModule, AuxTablesRoutingModule, SharedModule]
})
export class AuxTablesModule {}
在另一个模块上作为 Lazy 导入:
const routes: Routes = [
{
path: AIRPORTS_ROUTES.AUX_TABLES.route,
loadChildren: () => import('./aux-tables/aux-tables.module').then(m => m.AuxTablesModule)
}
...
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class AirportsRoutingModule {}
这是一种魅力。但是现在我需要完全相同的模块,在另一个模块中具有相同的视图和行为,但是我需要更改负责从另一个 API 获取数据的提供程序。所以我想更改 AuxTablesService 和 AuxTableDataResolverGuard。
我正在尝试这样的事情: 将其导入另一个模块,在本例中为 TrainsModule
const routes: Routes = [
{
path: TRAINS.AUX_TABLES.route,
loadChildren: () => import('./aux-tables/aux-tables.module').then(m => m.AuxTablesModule
.forChild(newApiProvider, newResolverGuard))
}
...
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class TrainsRoutingModule {}
并准备 AuxTablesModule 以接收这样的自定义提供程序:
@NgModule({
declarations: [AuxTablesComponent, AuxTablesListingComponent],
providers: [AuxTablesService, AuxTableDataResolverGuard],
imports: [CommonModule, AuxTablesRoutingModule, SharedModule]
})
export class AuxTablesModule {
static forChild(auxTableApiService: AuxTablesService, auxTableGuardResolver: Resolve<IAuxTable>) {
return {
ngModule: AuxTablesModule,
providers: [
{
provide: AuxTablesService,
useClass: auxTableApiService
},
{
provide: AuxTablesService,
useClass: auxTableGuardResolver
}
]
};
}
}
但是当 Angular 尝试渲染 forChild 惰性模块时,我得到了这个错误:
core.js:6014 ERROR 错误:未捕获(承诺中):错误:未找到“[object Object]”的 NgModule 元数据。
Debbuing 角度,返回 Object 不是构造函数,不能作为模块“分解”,也不能在其上找到元数据作为 @ngModule。 有没有人知道怎么做这样的事情?喜欢为延迟加载的模块提供自定义类?
【问题讨论】:
-
我认为您正在寻找 FactoryProviders:stackoverflow.com/a/60304854/6455844
-
不:/,我可以将提供程序更改为 factoryProvider,这很好,问题是作为 LazyLoaded 模块导入,我无法使用任何类型的配置来实例化模块。
-
我有一个解决方法,但似乎没有采用正确的设计模式。我已经从要延迟加载的模块中删除了提供程序。并在延迟加载模块的调用模块上传递提供者,所以基本上,延迟加载模块寻找提供者并没有找到它,所以我从调用模块中获取它。但似乎不对,我真的希望我的模块有自己的提供程序,并且能够在需要时懒惰地覆盖原来的提供程序。
标签: angular angular8 angular2-modules