【问题标题】:Angular Module Federation and remote servicesAngular Module Federation 和远程服务
【发布时间】:2022-08-06 08:24:02
【问题描述】:

我在几个微前端分解一个 Angular 网络。其中一个微前端处理购物车,它具有存储已添加产品的服务。我的 shell 微前端需要使用该服务在图标中显示汽车中有多少物品,添加新物品等。

我可以在存储在不同微前端中的微前端中使用服务吗?

我正在使用这个tutorial,但它只解释了如何路由另一个微前端中的页面。

谢谢。

    标签: angular micro-frontend webpack-module-federation


    【解决方案1】:

    我可以在存储在不同微前端的微前端中使用服务吗?

    不。微前端中的代码不会相互共享。

    您需要在存储库中创建一个库项目。该库将在您的微应用程序之间共享。在这里,您可以创建一个服务,用于存储一些数据并在应用程序之间共享。

    https://angular.io/guide/creating-libraries

    正在使用 Nx 工作区:https://nx.dev/workspace/library

    【讨论】:

    • 项目库不需要在同一个存储库中,OP 也可以使用 NPM 将其安装在两个 MFE 上。如果 OP 想要在 2 个 MFE 之间共享数据,则需要一个单例,为此必须将其添加到 webpack.config.js 文件的 shared 属性中。
    【解决方案2】:

    你可以这样做。

    // 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
     });
    

    【讨论】:

      猜你喜欢
      • 2021-10-23
      • 2022-08-04
      • 2022-12-03
      • 2022-10-15
      • 1970-01-01
      • 2022-10-31
      • 2021-08-15
      • 2015-11-11
      • 1970-01-01
      相关资源
      最近更新 更多