What was wrong with yesterday’s code example? Here it is as a reminder:
Since the developer used the shareReplay
operator, the intent was to cache the result of the HTTP request so that we do not make that request repeatedly.
The problem is that if several components call the getData()
method, they all get a brand new Observable since the method returns a new request every time, which defeats the purpose of using shareReplay
.
How can we fix this? By creating the Observable once then sharing the results in subsequent calls to getData():
Here’s another way to do it, perhaps even more readable:
Why do these solutions work? DataService
is a singleton, which means all components use the same instance of DataService
. As a result, any property of DataService
(such as cache$
) is the same for all components that access it.
Another critical thing to note is that HTTP requests are cold observables, which means they only fire when a subscriber subscribes to them.