BoazGarty
BoazGarty

Reputation: 1446

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

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?

Upvotes: 4

Views: 14881

Answers (2)

Andrew Allen
Andrew Allen

Reputation: 8042

Question is unfocused but I'll bite.

Ways of saving data in increasing complexity are:

  • using a collection service with your own interface of methods (addWidget, removeWidget etc.) that injects the api service
  • using a caching service and http interceptor Angular - HttpClient -Caching
  • using a rxjs + facade (there's a talk from ng-conf on push based services)
  • using ngrx (I recommend @ngrx/data if you have control over the api design and @ngrx/entity otherwise)

These are all "online" so that app refresh loses the data and refresh api calls would be needed (which isn't necessarily a bad thing).

Good principles and rules of thumb:

  • break your api response into entities (e.g. using normalizr) so that your front end only has to update state is one place only
  • use interfaces liberally for both the api response, broken down entity model and view models for the components which combines state (several entities)
  • use container/component pattern - container to handle getting, combining the data or dispatching state changes and component only knows have to recieve data and notify container of events
  • if using ngrx a good pattern is API → normalizr → entities → store

Upvotes: 2

andriishupta
andriishupta

Reputation: 577

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.

Upvotes: 11

Related Questions