简体   繁体   English

如何在 nx 模块联合中使用 BehaviorSubject?

[英]How to use BehaviorSubject in nx module federation?

I have this module federation workspace我有这个模块联合工作区

apps
-- host
---- src
------ app
-------- app.component.ts
-- main
---- src
------ app
-------- app.component.ts
libs
-- components
---- menu
------ src
-------- lib
---------- menu.component.ts
-- services
---- src
------ lib
-------- global.service.ts

global.service.ts全局服务.ts

items$ = new BehaviorSubject<any[]>([]);

setMenuItems(items: any[]): void {
    this.items$.next(buttons);
}

menu.component.ts菜单.component.ts

items: any[];

ngOnInit(): void {
    this.globalService.items$.subscribe((result) => {
        this.items = result;
    });
}

host app - app.component.ts主机应用程序 - app.component.ts

ngOnInit(): void {
    this.globalService.setMenuItems([1, 2, 3]); // this works
}

main app - app.component.ts主应用程序 - app.component.ts

ngOnInit(): void {
    this.globalService.setMenuItems([1, 2, 3]); // this not works
}

I can't use global service in my main app.我无法在我的主应用程序中使用全球服务。
This is the command I use to run the project: nx serve host--devRemotes="main"这是我用来运行项目的命令: nx serve host--devRemotes="main"

That might be because you're not coding reactively.那可能是因为您没有进行被动编码。

Try this instead.试试这个。

@Component(...)
export class MenuComponent {
  items$ = this.globalService.items$.asObservable();

  constructor(private globalService: GlobalService) {
}
<div class="menu">
  <div *ngFor="let item of items$ | async" class="menu-item">{{ item }}</div>
</div>

Do you use injectable decorator in service class declaration with provideIn: 'root'?您是否在带有 provideIn: 'root' 的服务类声明中使用可注入装饰器?

@Injectable({
  providedIn: 'root'
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Angular 和 Nx monorepo 上使用 Module Federation 托管资产 - How to host assets with Module Federation on Angular and Nx monorepo Nx 模块与 Angular 联合 - 没有 HttpClient 提供程序 - Nx Module Federation with Angular - No provider for HttpClient 如何使用带有模块联合和 NX 的通用 shell 创建基于不同技术的微前端? - How to create micro frontends based on different technologies using a common shell with module federation and NX? Webpack 5 Module Federation 微前端和 Nx monorepos 是否相互排斥? - Are Webpack 5 Module Federation micro frontends and Nx monorepos mutually exclusive? 如何在 behaviorSubject 上使用 shift? - how to use shift on behaviorSubject? 如何将 BehaviorSubject 与 Observable 一起使用 - how to use BehaviorSubject with Observable 如何使用 Behaviorsubject 来检测变化 - How to use Behaviorsubject to detect change Angular、Nx 工作区、Webpack 5 模块联合:您提供了一个预期流的无效对象 - Angular, Nx Workspace, Webpack 5 Module Federation: You provided an invalid object where a stream was expected 不适用于来自 nx(模块联合)的生产程序集 remoteEntry.mjs - Does not work in the production assembly remoteEntry.mjs from nx (Module Federation) 模块联合中的共享库:如何提供? - Shared library in module federation: how to provide it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM