gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:02:48 25 4
gpt4 key购买 nike

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

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

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

所以我在文章Load new modules dynamically in run-time with Angular CLI & Angular 5之后搜索了更多我尝试了 System.Js 方法,但找不到 angular 9 的工作解决方案。

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

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

最佳答案

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

我假设插件是 元素 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();
}
}

以及它的 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>

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

现在我不得不为每个插件组件动态添加路由路径。
在我的 App 组件中,我创建了这个简单的方法:
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 });
});
});
}

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

我希望这可以帮助某人。

关于Angular App 无需重新编译即可动态加载插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60547447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com