【发布时间】:2019-07-16 11:09:43
【问题描述】:
问题:
我正在为 Angular 中的非路由模块设置延迟加载。在第 7 版中,我使用 NgModuleFactoryLoader 和它的函数 load 来延迟加载模块并获取模块的第一个入口点(以防万一)
this.loader.load('path-to-module')
.then(factory => {
const module = factory.create(this._injector);
return module.injector.get(EntryService);
});
但在 Angular 8 中 NgModuleFactoryLoader 已弃用,因此我必须以这种方式加载模块:
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-routable-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
【问题讨论】:
标签: angular angular8 angular-compiler angular-ivy