【发布时间】:2022-08-06 08:24:02
【问题描述】:
我在几个微前端分解一个 Angular 网络。其中一个微前端处理购物车,它具有存储已添加产品的服务。我的 shell 微前端需要使用该服务在图标中显示汽车中有多少物品,添加新物品等。
我可以在存储在不同微前端中的微前端中使用服务吗?
我正在使用这个tutorial,但它只解释了如何路由另一个微前端中的页面。
谢谢。
标签: angular micro-frontend webpack-module-federation
我在几个微前端分解一个 Angular 网络。其中一个微前端处理购物车,它具有存储已添加产品的服务。我的 shell 微前端需要使用该服务在图标中显示汽车中有多少物品,添加新物品等。
我可以在存储在不同微前端中的微前端中使用服务吗?
我正在使用这个tutorial,但它只解释了如何路由另一个微前端中的页面。
谢谢。
标签: angular micro-frontend webpack-module-federation
我可以在存储在不同微前端的微前端中使用服务吗?
不。微前端中的代码不会相互共享。
您需要在存储库中创建一个库项目。该库将在您的微应用程序之间共享。在这里,您可以创建一个服务,用于存储一些数据并在应用程序之间共享。
https://angular.io/guide/creating-libraries
正在使用 Nx 工作区:https://nx.dev/workspace/library
【讨论】:
webpack.config.js 文件的 shared 属性中。
你可以这样做。
// In your remote module
@NgModule({
declarations: [],
imports: [CommonModule],
providers: [YourRemoteService],
})
export class YourRemoteModuleModule {
public constructor(
@Inject(YourRemoteService) private readonly yourRemoteService: YourRemoteService
) {}
/**
* Allows the to access YourRemoteService.
*
* @returns The service instance.
*/
public getService(): YourRemoteService {
return this.yourRemoteService;
}
}
// In the module that wants to load a remote module/service
import { loadRemoteModule } from '@angular-architects/module-federation';
import type { LoadRemoteModuleOptions } from '@angular-architects/module-federation';
const options: LoadRemoteModuleOptions = {
remoteEntry: // your entry
remoteName: // your remote name
exposedModule: // your exposed module
};
from(loadRemoteModule(options)).pipe(
switchMap((module) => this.compiler.compileModuleAsync<YourContract>(module[YourModule])),
map((moduleFactory) => {
const moduleRef = moduleFactory.create(this.injector);
const instance = moduleRef.instance;
return instance.getService(); // Your contract
});
【讨论】: