问题:
我正在为角度的非路由模块设置延迟加载。在我使用的第 7 版中NgModuleFactoryLoader
,它的功能load
是延迟加载模块并获取模块的第一个入口点(以防万一)
this.loader.load('path-to-module')
.then(factory => {
const module = factory.create(this._injector);
return module.injector.get(EntryService);
});
但是在 Angular 8NgModuleFactoryLoader
中已弃用,所以我必须以这种方式加载模块:
import('path-to-module')
.then(m => m.MyModule)
.then(myModule => {
...
});
这里的问题是我无法在新的延迟加载中检索工厂并在此处获取提供者(IVY 的想法之一 - 没有工厂)。
我已经尝试过的:
第一个解决方案(仅使用不适合我们的 JIT 编译器,因为我使用 AOT 编译器进行生产)
import('path-to-module')
.then(m => m.MyModule)
.then(myModule => {
return this._compiler.compileModuleAsync(myModule)
.then(factory => {
const module = factory.create(this._injector);
return module.injector.get(EntryService);
});
});
第二种解决方案(肮脏且未完全检查。它正在使用ngInjectorDef
IVY 的新功能并且还没有任何描述的 API):
import('path-to-module')
.then(m => m.MyModule)
.then(myModule => {
const providers = myModule['ngInjectorDef'].providers; // Array<Providers>
... find EntryService in providers
});
ngInjectorDef
- 是一个静态模块类属性,由 Angular 添加,具有工厂、提供者和导入属性。
资料来源:
- https://netbasal.com/the-need-for-speed-lazy-load-non-routeable-modules-in-angular-30c8f1c33093(延迟加载不可路由的模块直到角度 8)
- https://herringtondarkholme.github.io/2018/02/19/angular-ivy/(IVY预览 - 见章节
No NgFactory file anymore
) - https://blog.angularindepth.com/automatically-upgrade-lazy-loaded-angular-modules-for-ivy-e760872e6084(描述 Angular < 8 和 Angular 8 中的延迟加载之间的差异。重要部分 - 从 NgModule 到 NgModuleFactory 与AOT编译器,现在基本上是我的问题)