在angular.js中缓存数据的常用方法是什么 [英] what's the common approach for caching data in angular.js

查看:76
本文介绍了在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);
            });
        }
    }
}

使缓存无效的常见方法是什么?我应该将其与当前日期进行比较吗? angular是否提供任何缓存失效机制?

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

使用cacheFactory代替持有高速缓存的变量有什么好处?

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

推荐答案

您可以检查 angular-cache ,这将避免您使用$ cacheFactory重新发明轮子(它仅提供简单的存储,有时就足够了).

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);
    });
  }
});

使用cacheFactory代替变量有什么好处 保持缓存?

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

此外,它还建立了可测试的服务,该服务实现了 LRU ,并为您节省了几行代码?没事.

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

这篇关于在angular.js中缓存数据的常用方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆