Reputation: 3556
This might be a very basic question, but I am really stuck in this situation and seem to be not able to figure out the answer be experiment:
I am doing a http GET request on some data. I have to display this data in a "component" and I later I would have to "access" this data (the one received from the http request).
So I have to store this data at two points. Would I just suscribe to the Observable returned from the http GET request twice? Or would I have to subscribe once, save the response somewhere and from that saved data feed my two use-case (the component and the access).
If I subscribe twice is there a chance of data loss, because the first subscription triggers the http GET and the second subscriptions "comes to late"?
If this seems to vague please let me know and I will insert some code also.
I am using @angular/core 7.0.0 and rxjs 6.3.3.
Upvotes: 1
Views: 188
Reputation: 7927
Your best option is to create a BehaviorSubject
that is associated with your HTTP call. You initiate the HTTP call with one function and then subscribe to the values with another. Therefore you are not always triggering the HTTP call if you don't want to.
Example:
...
// Service
private values: BehaviorSubject<any> = new BehaviorSubject<any>(null);
subscribeValues(): BehaviorSubject<number> {
return this.values;
}
public getValues(): void {
this.http.get(this.URL)
.toPromise()
.then(res => {
this.values.next(res);
});
}
...
...
// Component
ngOnInit() {
this.myService.subscribeValues().subscribe(value => {
// whatever
});
this.myService.getValues();
}
The BehaviorSubject
will always emit the last (or initial) value it has when you subscribe to it. So when you subscribe from any component you'll get the last value and from any component you can trigger the API again and anything that is subscribed will be updated.
Upvotes: 1
Reputation: 14149
If I subscribe twice is there a chance of data loss, because the first subscription triggers the http GET and the second subscriptions "comes to late"?
That depends on whether your observable is "hot" or "cold". There are many resources on this topic. But basically, hot is when an observable is shared by multiple subscribers and cold is when a new observable is created for each subscriber.
Angular's httpClient.get
gives you a cold observable. That means, each time you subscribe to it, you trigger a new http request.
But it's really easy to convert a cold observable into a hot one. You do it by using the share
operator. For example:
this.httpClient.get("https://google.com").pipe(share())
However, this will cause "late subscribers" to miss the notifications. If you have two subscribers and want them both to get the notification guaranteed, you'd use shareReplay(1)
this.httpClient.get("https://google.com").pipe(shareReplay(1))
This will cache the last notification and give it to each subscriber on subscribe, making sure you only call HTTP once and every subscriber gets a result.
Upvotes: 3