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.
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
Asked: 2023-03-02 11:00:00 +0000
Seen: 11 times
Last updated: Sep 25 '22
What are the possible situations in which microservices can fail?
How can the argument of Jest Mock Service be made assignable?
What does it mean when API Gateway gives a 503 Service Unavailable error?
How can dependency injection be implemented for classes in Stripe.Net?
What is the process of uploading files to OSS cloud service using Flutter?