Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the common approach for caching data in angular.js

Suppose I have a service that retrieves a list of tags and I store tags in the cache:

function TagsRetriever() {

    var cache = $cacheFactory("tags");
    function getTags() {
        var cached = cache.get("tags");
        if (cached) {
            return cached;
        } else {
            return $http.get("url/getTags").then(function (tags) {
                cache.put("tags", tags);
            });
        }
    }
}

What is the common approach to invalidate the cache? Should I compare it to current date? Does angular provide any mechanism of cache invalidation?

And what's the benefit of using cacheFactory instead of a variable holding cache?

like image 418
Max Koretskyi Avatar asked Oct 19 '22 14:10

Max Koretskyi


2 Answers

cacheFactory basically gives you a place to store stuff in memory as a service. It provides an interface to interact with the cache, and it is available anywhere you inject the service.

It doesn't appear to have anything specific for doing invalidation. Just include a date key whenever you put() and check against it.

Oliver's usage is excellent as well. Stream data to the cache through sockets and then just get from the cache. If you aren't doing it this way though, you could create a service that handles the cache validation. Pass the data to the service. If it's new data, it adds a date key. If it's existing data, compare dates.

It has the following methods:

  • put, get, remove, removeAll, info, destroy

There really isn't much to it: Documentation

like image 151
tpie Avatar answered Oct 22 '22 03:10

tpie


You may check brilliant angular-cache which will keep you from re-inventing the wheel with $cacheFactory (it provides nothing but simple storage, sometimes it's enough).

That's how it handles cache invalidation (an example from the manual):

CacheFactory('profileCache', {
  maxAge: 60 * 60 * 1000 // 1 hour,
  deleteOnExpire: 'aggressive',
  onExpire: function (key, value) {
    $http.get(key).success(function (data) {
      profileCache.put(key, data);
    });
  }
});

And what's the benefit of using cacheFactory instead of a variable holding cache?

Besides it establishes testable service that implements LRU and saves you a few lines of code? Nothing.

like image 25
Estus Flask Avatar answered Oct 22 '22 03:10

Estus Flask