1 | initial version |
One way to load data from an Angular Service into two components simultaneously is to use the RxJS BehaviorSubject.
private data = new BehaviorSubject<any>(null);
getData() {
// load data from API or other source
const data = [1, 2, 3];
// update BehaviorSubject value
this.data.next(data);
}
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.