简体   繁体   中英

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

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"

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'?

@Injectable({
  providedIn: 'root'
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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