【问题标题】:Loading dynamic module from another url- angular4从另一个 url-angular4 加载动态模块
【发布时间】:2017-08-08 14:37:52
【问题描述】:

是否可以引用一个模块(已编译为 umd 或 es 格式)并在已编译的 Angular 应用程序中动态加载它?

  1. 主 shell 应用程序托管在:http://plugin_shell.mydomain.com
  2. 一个模块(带有一堆组件、服务等):编译后的代码 托管在另一个 url。让我们说: http://plugins/modules/myfirstplugin.umd.js
  3. 外壳加载时。加载所有模块,渲染特定组件,参考 到服务、使用类等。

我尝试使用 SystemJsNgModuleLoader.load 加载模块,但它似乎确实适用于这种用例。

谢谢

编辑:同样的问题(没有答案):How to dynamically load external angular 2 module (like served from an external module.bundle.js)

【问题讨论】:

  • 您说的是编译好的 ng 应用程序(又名 webpack 片段),但您还提到了 systemJS,您使用的是哪一个?
  • shell 是一个 webpack 应用程序。所有的模块,必须是动态的,所以它们目前被编译为带有汇总的 umd 模块。这里的问题是模块将被更新并在一个 url 上发布。 shell 必须从 url 加载它们(并具有可用的最新版本)。
  • github.com/webpack/webpack/issues/150 这可能会对您有所帮助,但是因为我不知道它是如何完成的,所以我不会将其作为答案发布。似乎人们在这个问题上实现了您想要做的事情。

标签: angular dynamic


【解决方案1】:

你可以这样做:

@Component({
  providers: [
    {
      provide: NgModuleFactoryLoader,
      useClass: SystemJsNgModuleLoader
    }
  ]
})
export class ModuleLoaderComponent {
  constructor(private _injector: Injector,
              private loader: NgModuleFactoryLoader) {
  }

  ngAfterViewInit() {
    this.loader.load('app/t.module#TModule').then((factory) => {
      const module = factory.create(this._injector);
      const r = module.componentFactoryResolver;
      const cmpFactory = r.resolveComponentFactory(AComponent);

      // create a component and attach it to the view
      const componentRef = cmpFactory.create(this._injector);
      this.container.insert(componentRef.hostView);
    })
  }
}

阅读Here is what you need to know about dynamic components in Angular 了解更多详情。特别是Dynamic module loading and compilation 部分。

【讨论】:

  • 但是当模块在已编译的应用程序中烘焙时,此代码很好。我的外壳已经编译,模块/组件完全来自另一个来源。例如我想在开发中做:const url: string = 'http://localhost:8082/core/core.umd.js'; System.import(url).then((module) => { ...
  • 我有类似的要求@ThePainnn 你能解决这个问题吗?如果是这样,请分享详细信息。谢谢
  • @ThePainnn,Webpack 不能这样做,这是正确的。我为此使用 SystemJS
  • @meno,没有解决方法,因为 Webpack 并非设计为模块加载器。我在我的项目中同时使用了 webpack 和 SystemJS。
  • @ANewGuyInTown,是的,它可以加载模块,但只能加载那些在构建时已知的模块。它不能像import() 那样动态加载模块
猜你喜欢
  • 2018-04-27
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多