Ask Your Question
1

What is the way to load data from an Angular Service into two components simultaneously?

asked 2023-03-02 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-09-25 19:00:00 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-02 11:00:00 +0000

Seen: 11 times

Last updated: Sep 25 '22