Home > Software engineering >  How to use BehaviorSubject in nx module federation?
How to use BehaviorSubject in nx module federation?

Time:12-21

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

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

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

menu.component.ts

items: any[];

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

host app - app.component.ts

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

main app - 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"

CodePudding user response:

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 >
  <div *ngFor="let item of items$ | async" >{{ item }}</div>
</div>

CodePudding user response:

Do you use injectable decorator in service class declaration with provideIn: ‘root’?

@Injectable({
  providedIn: 'root'
})
  • Related