如何在NX Module Federation中使用BehaviorSubject?主应用调用全局服务失效
问题解决:NX Module Federation远程应用无法使用全局服务
1. 先修正代码笔误
首先看global.service.ts里的明显错误:setMenuItems方法中调用next时用了未定义的buttons,应该替换为参数items:
// libs/services/src/lib/global.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class GlobalService { items$ = new BehaviorSubject<any[]>([]); setMenuItems(items: any[]): void { this.items$.next(items); // 替换buttons为items } }
2. 配置Module Federation共享单例服务
问题核心是:默认情况下Host和Remote应用会各自实例化GlobalService,导致两者不是同一个实例。需要通过Module Federation配置将服务设为全局共享单例。
配置Host应用
修改apps/host/module-federation.config.ts,添加共享配置:
export default { name: 'host', remotes: ['main'], shared: { '@angular/core': { singleton: true, strictVersion: true }, '@angular/common': { singleton: true, strictVersion: true }, '@angular/router': { singleton: true, strictVersion: true }, 'rxjs': { singleton: true, strictVersion: true }, // 替换为你的services库实际导入路径(查看libs/services/package.json的name字段) '@your-workspace/services': { singleton: true, strictVersion: true } } };
配置Remote应用(main)
修改apps/main/module-federation.config.ts,同步共享配置:
export default { name: 'main', exposes: { // 保留你已有的暴露配置,比如: './Module': './src/app/app.module.ts' }, shared: { '@angular/core': { singleton: true, strictVersion: true }, '@angular/common': { singleton: true, strictVersion: true }, '@angular/router': { singleton: true, strictVersion: true }, 'rxjs': { singleton: true, strictVersion: true }, '@your-workspace/services': { singleton: true, strictVersion: true } } };
3. 确保Remote应用正确导入服务
在main应用的app.component.ts中,确认从共享库导入服务:
// apps/main/src/app/app.component.ts import { Component, OnInit } from '@angular/core'; import { GlobalService } from '@your-workspace/services'; // 从共享库导入 @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor(private globalService: GlobalService) {} ngOnInit(): void { this.globalService.setMenuItems([1, 2, 3]); // 现在可正常生效 } }
4. 重启服务
停止当前运行的nx serve host --devRemotes="main"命令,重新执行该命令,确保配置生效。
内容的提问来源于stack exchange,提问作者Reza
相关产品推荐
相关产品推荐

