It's time for another Angular Knowledge Pill! π
It takes just 10 seconds to learn something new π₯
Like taking your morning vitamins π
Below code presents how to cache HTTP requests in Angular!
First, we just need to execute a regular HTTP query (for ex. get) and pipe the stream through shareReplay operator! This transforms the initial stream to a ReplaySubject! In other words, new subscriptions will NOT execute other HTTP requests but a cached value will be used π
If you would like to receive this kind of knowledge pills directly into your mailbox, subscribe at https://angular-academy.com/blog/. I will be sending them regularly! Remember, it just takes 10 seconds to learn something new!
Top comments (11)
I struggled figuring this out for at least 1 month when I started with Angular. I looked up a million different approaches and they all were "ugly" or didn't work how I wanted.
I eventually stumbled upon the same solution you gave and found it is hands down the easiest and best way to cache http-requests.
Hopefully this article helps out those out there who need this!
Another cool feature of this approach is it shares the ongoing request with all the subscribers, so if 10 "subscribers" show up asking for this data you still make 1 request, and pass the same data to everyone π
πππ
Going through the discussion, everyone had the same question how to invalidate the cache, but that link you are providing is not that clear, can you point to some other link where there is a more detailed overview of the methods?
Everyone's asking how to invalidate the cache and you suggest to make another stream, but what if you simply reset the observable to undefined when the data is altered from another function? Wouldn't that essentially remove the reference to the observable and force it to call the backend again?
Hi Bartosz! Thanks for sharing this tip. I would like to ask you if you found any way to invalidate this cache? Thanks!
Hi! You can create another stream without shareReplay and fetch the data or set a timeout (windowTime) on shareReplay (rxjs-dev.firebaseapp.com/api/opera...).
Thanks again! I'll give a try :)
Great tip.
How would you clear the cache though if you wanted to make a new request?
Hi! You can create another stream without shareReplay and fetch the data or set a timeout (windowTime) on shareReplay (rxjs-dev.firebaseapp.com/api/opera...).
Thanks Bartosz Pietrucha , TIL about this.
Does this mean everytime a request is made records will be served from the cache except first request.
How can i invalidate this and make a fresh request ?
Hi Sanket Maru! Yes, that's the idea of the cache.
Regarding invalidation, you can create another stream without shareReplay and fetch the data or set a timeout (windowTime) on shareReplay (rxjs-dev.firebaseapp.com/api/opera...).