具有单例服务的URL的Lazyload Angular模块

时间:2019-06-24 13:06:07

标签: angular typescript lazy-loading angular7 systemjs

如何延迟加载角度模块并将服务公开为单例?

  • 应用延迟加载ModA和ModB
  • ModAComponent将一些数据放入ModAService
  • ModB从ModAService获取数据

但是:

  • 我不知道任何模块名称
  • 我在编译时没有任何模块(它们是外部模块)
  • 任何人都可以将模块上传到文件夹中
  • 我必须从URL延迟加载模块并使用它

基于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


  • 有什么方法可以将SystemJS用作单例服务来使用公开的服务加载模块?
  • 是否可以使用SystemJsNgModuleLoader从URL(例如外部)加载模块?
  • 还有其他选择吗?

谢谢!

0 个答案:

没有答案