繁体   English   中英

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

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

我有这个模块联合工作区

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

全局服务.ts

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

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

菜单.component.ts

items: any[];

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

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

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

主应用程序 - app.component.ts

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

我无法在我的主应用程序中使用全球服务。
这是我用来运行项目的命令: nx serve host--devRemotes="main"

那可能是因为您没有进行被动编码。

试试这个。

@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>

您是否在带有 provideIn: 'root' 的服务类声明中使用可注入装饰器?

@Injectable({
  providedIn: 'root'
})

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM