Angular App 无需重新编译即可动态加载插件

Fab*_*ari 6 plugin-architecture web-frontend angular system.js

我正在尝试开发 Web Api (NET CORE) 可插件应用程序的前端。我想使用 Angular 9,但我不是 Angular 专家。

我的后端被设计为可扩展的,在启动时它会在指定的文件夹中监视,如果存在一个或多个包含扩展基本应用程序(如插件)逻辑的 dll 文件,它会加载它们。我想在前端使用类似的方法。我尝试了不同的解决方案并阅读了很多文章,但很难找到想要在编译时导入未知插件的人。

我尝试了懒惰的模块(从这个开始:https : //www.mokkapps.de/blog/manually-lazy-load-modules-and-components-in-angular/)这将是完美的,但使用这个我必须知道实现插件(模块)在编译我的 angular 应用程序之前,因为如果我想使用模块,我必须在我的主应用程序中使用导入功能。

因此,我进行了更多搜索,在使用 Angular CLI 和 Angular 5 在运行时动态加载新模块一文之后,我尝试了 System.Js 方法,但找不到适用于 angular 9 的解决方案。

我很确定我不是唯一一个会创建可插入的 Angular 应用程序的人,该应用程序无需重新编译主应用程序即可加载插件。

我需要一些关于正确方法的建议,或者一个使用插件架构的 angular 应用程序的工作示例。

Fab*_*ari 0

我不确定这是更好、更优雅的解决方案,因为我是 Angular 的新手,但它目前对我有用。

我假设插件是Element Web 组件( https://angular.io/guide/elements )。为了创建我的第一个元素(插件),我遵循了本教程: https: //www.techiediaries.com/angular/angular-9-elements-web-components/

顺便说一句,此时我无法动态加载插件,因为在编译项目以使用它之前,我必须知道在元素中部署的组件的名称。我使用扩展元素找到了解决方案(https://angular-extensions.github.io/elements/#/home)。因此,我创建了一个动态组件,用于在运行时显示插件的组件。

这是动态组件的代码:

export class DynamicComponentContainerComponent implements OnInit {
  plugin: Plugin
  sub: any;

  constructor(private route: ActivatedRoute, private pluginService: PluginService) { }

  ngOnInit() {
    this.sub = this.route
      .data
        .subscribe(data => {
           this.pluginService.getPlugin(data['pluginName'])
            .subscribe(
              (res) => {
                this.plugin = res;
              },
              (err) => {
                console.error(err)
              } 
            );
          });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}
Run Code Online (Sandbox Code Playgroud)

及其 html 模板:

<div *ngIf="plugin != null">
<ng-template #loading>Loading plugin {{plugin.tag}} ...</ng-template>
<ng-template #error>Error Loading plugin {{plugin.tag}}</ng-template>
<ax-lazy-element
    *axLazyElementDynamic="plugin.tag; url: plugin.url; module: plugin.isModule; 
errorTemplate: error; loadingTemplate: loading;">
</ax-lazy-element>
</div>
Run Code Online (Sandbox Code Playgroud)

它可以工作,因为我的后端提供插件的 JS 编译文件(Element Web Component),所以我必须在使用它之前注册我的插件(因为我需要一些值来处理它,例如组件的名称或路由的路径)。事实上,动态组件中的axLazyElementDynamic属性需要 JS Element Web 组件文件的 url 和组件名称才能工作。

现在我必须动态地添加每个插件组件的路由路径。在我的应用程序组件中,我创建了这个简单的方法:

loadPlugins() {
  this.pluginService.getPlugins()
    .subscribe(plugins => {
      plugins.forEach(plugin => {
        this.router.config.unshift({ path: plugin.path, component: 
DynamicComponentContainerComponent, data: { pluginName: plugin.name } });
        this.links.push({ text: plugin.description, path: plugin.path });
      });
    });
}
Run Code Online (Sandbox Code Playgroud)

插件服务只是从后端(我之前注册插件的地方)获取插件数据。

我希望这可以帮助别人。