Search code examples
angularcachingsingleton

Angular saving http response along application


On my application I defined a service to call my api to retrieve some data. This data, on api side, comes from a database table that only changes like 1 time/year, and therefore I'd like to retrieve this data only one time (to increase the app performance).

I try using cache (for instance this example) but it doesn't fit very well on this case because whenever my user refresh the page the api is called again.

My goal is "lost" my values only when my application is restarted or after some defined amount of time.

What's the best way to do it? Something like having a singleton?


Solution

  • You could use the localstorage to save this data. You mentioned two scenarios for cache busting -

    1. Defined amount of time
    2. Application restarted

    you can achieve both by setting extra "metadata" on the items you save - timestamp for when you first saved the data, and a hash for your application (which you will need to set in your code). This way, when getting the item, you can check both the version and the date inserted, if one of those doesnt meet your conditions, delete the localStorage entry and fetch from the server.

    All this logic should be implemented in your service (preferably as generic code which can be easily repeated for different calls (maybe a decorator?)