【问题标题】:How to use BehaviorSubject in nx module federation?如何在 nx 模块联合中使用 BehaviorSubject?
【发布时间】:2022-12-21 04:33:37
【问题描述】:

我有这个模块联合工作区

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"

【问题讨论】:

    标签: angular angular-module-federation


    【解决方案1】:

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

    试试这个。

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

    【讨论】:

    【解决方案2】:

    你在 provideIn: ‘root’ 的服务类声明中使用可注入装饰器吗?

    @Injectable({
      providedIn: 'root'
    })
    

    【讨论】:

      猜你喜欢
      • 2021-07-06
      • 2022-12-15
      • 1970-01-01
      • 2020-10-07
      • 2022-11-04
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-05-11
      相关资源
      最近更新 更多