You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@angular-architects/module-federation,跨仓库Angular微前端如何共享数据?

Angular微前端(Module Federation)壳应用与微前端的数据共享方案

当然有,基于@angular-architects/module-federation的Angular微前端架构中,壳应用与微前端之间有多种成熟的数据共享方案,以下是最常用的几种:

1. 共享模块(Shared Library)

将需要跨应用共享的数据模型、状态管理服务抽离为独立的共享库,通过Module Federation的共享配置让壳应用和所有微前端复用同一个服务实例,以此实现数据同步。

  • 实现步骤:
    • 创建独立的共享库(例如@shared/core),包含一个带BehaviorSubject的共享服务:
      // shared-data.service.ts
      import { Injectable } from '@angular/core';
      import { BehaviorSubject } from 'rxjs';
      
      @Injectable({ providedIn: 'root' })
      export class SharedDataService {
        private userData$ = new BehaviorSubject<any>(null);
        public userDataObs$ = this.userData$.asObservable();
      
        updateUserData(data: any) {
          this.userData$.next(data);
        }
      }
      
    • 在壳应用和所有微前端的module-federation.config.ts中配置共享:
      shared: {
        '@angular/core': { singleton: true, strictVersion: true },
        '@angular/common': { singleton: true, strictVersion: true },
        '@shared/core': { singleton: true, strictVersion: true }
      }
      
    • 壳应用和微前端只需注入SharedDataService,通过updateUserData()更新数据,userDataObs$订阅数据变化即可实现同步。

2. 浏览器自定义事件(Custom Events)

利用浏览器原生的自定义事件API,通过window对象传递数据,适合简单、低耦合的跨应用通信场景。

  • 实现示例:
    • 壳应用发送数据:
      // 壳应用组件中
      window.dispatchEvent(new CustomEvent('user-updated', {
        detail: { userId: 123, username: 'Shinu Thomas' },
        bubbles: true,
        cancelable: true
      }));
      
    • 微前端监听数据:
      // 微前端组件中
      ngOnInit() {
        this.eventListener = (event: CustomEvent) => {
          const userData = event.detail;
          // 处理数据逻辑
        };
        window.addEventListener('user-updated', this.eventListener);
      }
      
      ngOnDestroy() {
        window.removeEventListener('user-updated', this.eventListener);
      }
      
    • 注意:务必在组件销毁时移除事件监听,避免内存泄漏。

3. 暴露/导入跨应用服务

通过Module Federation的exposes配置,将壳应用的服务暴露给微前端,或者让微前端的服务被壳应用调用,直接复用同一个服务实例实现数据共享。

  • 实现示例:
    • 壳应用在module-federation.config.ts中暴露服务:
      exposes: {
        './ShellStateService': './src/app/services/shell-state.service.ts'
      }
      
    • 微前端在配置中导入该服务并设为单例:
      shared: {
        './ShellStateService': { 
          singleton: true, 
          import: 'shell-app/ShellStateService' 
        }
      }
      
    • 微前端可直接注入ShellStateService,与壳应用使用同一个实例,实现数据双向同步。

4. URL参数/路由状态传递

通过URL查询参数或路由状态传递数据,适合页面跳转场景下的一次性数据传递,无需依赖额外服务。

  • 实现示例:
    • 壳应用导航到微前端路由时携带参数:
      this.router.navigate(['/micro-app-2'], {
        queryParams: { projectId: 'PROJ-789' },
        state: { projectName: 'Angular MF Demo' }
      });
      
    • 微前端获取参数:
      // 获取查询参数
      this.route.queryParams.subscribe(params => {
        const projectId = params['projectId'];
      });
      
      // 获取路由状态
      const projectName = this.router.getCurrentNavigation()?.extras.state?.['projectName'];
      

内容的提问来源于stack exchange,提问作者Shinu Thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 08:05:37