What is the general approach for caching data in angular.js

Suppose I have a service that retrieves a list of tags, and I store the tags in a 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 general approach to invalidating a cache? Should I compare it with the current date? Does angular provide any cache invalidation mechanism?

And what is the use of using cacheFactory instead of a variable storage cache?

+5
source share
2 answers

You can check out the brilliant angular-cache , which won't let you reinvent the wheel with $ cacheFactory (it provides nothing but simple storage, sometimes that's enough).

How it handles cache invalidation (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 use of using cacheFactory instead of a cache storage variable?

In addition, it installs a testable service that implements LRU and stores several lines of code? Nothing.

+1
source

cacheFactory basically provides you with a place to store files in memory as a service. It provides an interface for interacting with the cache, and it is available anywhere you enter the service.

It does not seem to have anything concrete to do with invalidation. Just add a date key whenever you put () and check it.

Oliver's use is also excellent. Stream data to the cache through sockets, and then just get it from the cache. If you do not, you can create a service that handles cache validation. Submit data to the service. If this is new data, it adds a date key. If this is existing data, compare the dates.

It has the following methods:

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

There really isn’t so much: Documentation

+2
source

All Articles