Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to load data from an Angular Service into two components simultaneously is to use the RxJS BehaviorSubject.

  1. In your service, create a new BehaviorSubject:
private data = new BehaviorSubject<any>(null);
  1. In your data loading method, set the value of the BehaviorSubject:
getData() {
  // load data from API or other source
  const data = [1, 2, 3];

  // update BehaviorSubject value
  this.data.next(data);
}
  1. In each component, subscribe to the BehaviorSubject:
ngOnInit() {
  this.myService.data.subscribe((data: any) => {
    this.myData = data;
  });
}

This way, when the data is loaded in the service, both components will receive the updated data. Note that the BehaviorSubject will always emit the last value to all subscribers, even if they subscribe after the value has been updated.