Sharing Observables: Preventing Identical Http Calls
Assume the following case: You have an Angular/Ionic project that has multiple components that need the same resource. When the app loaded, the components will start getting the fresh data from the backend. Hence you will probably see multiple identical calls in the Network tab.
I created a mock up project to simulate the issue. I created 3 components which are almost identical and placed them twice in the parent component. When they are initialized, they try to get books array from the back end.
The result is 6 identical api calls.
One easy solution is to share observables. Share is an rxjs operator that you can easily implement.
this._ongoingObservable = this.http.get('someurl')
this._ongoingObservable = null;
What we do here is quite simple. We created a variable to keep a reference to the ongoing request. In the method, we first check if it has a value, if it has return it. If not, that means there is not an active request. Make a request and share
it so that this can become a multicast observable. Also make sure to remove the reference once we get a response from the request. Hence, we clear the variable in finalize
This will not cache the value, it will only prevent multiple identical requests.
Here is the result:
Subscribe to get your daily round-up of top tech stories!