Angular 2 observable subscribing twice executes call twice
You may use the share
operator on your result from HttpClient.get
, like this:
var observable = this.httpClient.get('api/version/secured', { headers: httpHeaders })
.pipe(share());
You'll need to add the following import on top of your script:
import { share } from 'rxjs/operators';
The share
operator makes an observable hot
, i.e. shared between subscribers. But there's a lot more to it, I would suggest this article to dive deeper (you can of course also google up hot vs cold observables
to find more).
Your observable is cold:
An observable is cold if the producer of its notifications is created whenever an observer subscribes to the observable. For example, a timer observable is cold; each time a subscription is made, a new timer is created.
You need to multicast
your Observable, or in other words, to make it hot:
An observable is hot if the producer of its notifications is not created each time an observer subscribes to the observable. For example, an observable created using fromEvent is hot; the element that produces the events exists in the DOM — it’s not created when the observer is subscribed.
For this you can use share operator, but it still cannot guarantee you a single http call. Share will multicast
your observable, making it shared between the subscribers, but once the http call completes it will make a new http call for new subscribers.
If you want a caching behavior (performing the call once and then providing the value to each subscriber whenever it subscribes) you should use publishReplay().refCount()
.
Further reading:
Publish and share operators