如何延迟加载角度模块并将服务公开为单例?
但是:
基于https://itnext.io/how-to-build-a-plugin-extensible-application-architecture-in-angular5-736890278f3f
使用SystemJS加载UMD模块:
declare const SystemJS: any;
constructor(private compiler: Compiler,
private injector: Injector,
) {}
/**
* Get all file names (Modules) in system path (Backend)
*/
... for each Module found
SystemJS.import('/src/ModA.umd.js' & '/src/ModB.umd.js').then((moduleToCompile) => {
return this.compiler.compileModuleAsync(moduleToCompile['ModuleA' & 'ModuleB']);
}).then((modFac: NgModuleFactory<any>) => {
modFac.create(this.injector);
});
将模块组件加载到ViewChild中(与第1部分相同):
this.compiler.compileModuleAndAllComponentsAsync<any>(modFac.moduleType)
.then((factory) => {
// Get needed component
const myFactory = factory.componentFactories.filter((component) => {
return component.componentType.name === 'MyComponent';
})[0];
this.MyViewChild.createComponent(actionsFactory);
});
之后,ModAComponent将一些数据放入ModAService
但是ModB看不到ModAService的任何数据
mod-loader.service.ts:16 Loading Module ModLazyAModule
18:58:36.065 app.component.ts:40 Waiting before importing LazyModuleB
18:58:36.068 core.js:16829 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
18:58:36.146 mod-lazy-a.service.ts:11 ModLazyA Service constructor
18:58:36.147 mod-lazy-a.module.ts:13 ModLazyA Module constructor
18:58:36.147 mod-lazy-a.module.ts:15 Pushing data from ModLazyA Module constructor
18:58:36.147 mod-lazy-a.module.ts:17 data ["some Data from ModLazyA Module constructor"]
18:58:36.148 mod-lazy-a.component.ts:16 ModLazyA Component constructor
18:58:36.150 mod-lazy-a.component.ts:20 Pushing data from ModLazyA Component ngOnInit
18:58:36.150 mod-lazy-a.component.ts:22 data (2) ["some Data from ModLazyA Module constructor", "some Data from ModLazyA Component ngOnInit"]
18:58:37.640 mod-loader.service.ts:16 Loading Module ModLazyBModule
18:58:37.664 mod-lazy-a.service.ts:11 ModLazyA Service constructor
18:58:37.665 mod-lazy-b.module.ts:15 ModLazyB Module constructor
18:58:37.665 mod-lazy-b.module.ts:17 Getting data from ModLazyB Module constructor
18:58:37.665 mod-lazy-b.module.ts:18 data []
18:58:37.666 mod-lazy-b.component.ts:16 ModLazyB Component constructor
18:58:37.667 mod-lazy-b.component.ts:20 Getting data from ModLazyB Component constructor
18:58:37.667 mod-lazy-b.component.ts:21 data []
REPO:https://github.com/infnada/angularLazyTest
谢谢!