DEV Community

How to cache HTTP requests in Angular

Bartosz Pietrucha on September 11, 2019

It's time for another Angular Knowledge Pill! 💊 It takes just 10 seconds to learn something new 🔥 Like taking your morning vitamins 😃 Below code p...
Collapse
 
bradtaniguchi profile image
Brad

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 😄

Collapse
 
bartosz_io profile image
Bartosz Pietrucha

🎉🎉🎉

Collapse
 
shubhambattoo profile image
Shubham Battoo

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?

Collapse
 
cristianooo profile image
Cristiano Firmani

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?

Collapse
 
mauro_codes profile image
Mauro Garcia

Hi Bartosz! Thanks for sharing this tip. I would like to ask you if you found any way to invalidate this cache? Thanks!

Collapse
 
bartosz_io profile image
Bartosz Pietrucha

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...).

Collapse
 
mauro_codes profile image
Mauro Garcia

Thanks again! I'll give a try :)

Collapse
 
bespunky profile image
Shy Agam

Great tip.
How would you clear the cache though if you wanted to make a new request?

Collapse
 
bartosz_io profile image
Bartosz Pietrucha • Edited

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...).

Collapse
 
sanketmaru profile image
Sanket Maru

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 ?

Collapse
 
bartosz_io profile image
Bartosz Pietrucha

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...).