Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular show cached data and update the new data if needed data in background

Tags:

angular

I'm developing an Angular app that handles a massive amount of data from the server. So every API call can take up to 5 seconds and there are pages we have few API calls.

What I want to achieve is to save the data in cache for every page I'm visiting and if I navigate to the page again I will see the cached data immediately, call API to get new data and refresh only the component that their model has changed.

Now API calls are being done from ngOnInit method and the app show spinner until the results are shown.

Is there any best practice to achieve that behavior in Angular, other than saving the json in local-storage or something similar?

like image 407
BoazGarty Avatar asked Sep 02 '25 14:09

BoazGarty


1 Answers

TL;DR; google for "caching technics with RxJS"

The bigger answer:

There are several options:

  • save data to localStorage/sessionStorage if you need it to be persistent
  • save it in service as plain data(just some variable)
  • simulate state with something like BehaviorSubject and retrieve it latest value(article for example)
  • using caching with RxJS
  • use storage like NgRx, if you have one

...and many more depending on what you want, and how the code is constructed.

If I was you - I would pick the variant with BehaviorSubject as initial if it is a simple application and don't have a huge state and it's management.

like image 54
andriishupta Avatar answered Sep 05 '25 08:09

andriishupta