angularjs:如何向资源对象添加缓存?

iam*_*pal 42 javascript angularjs

在http中添加缓存非常简单.(通过传递cache = true)

http://docs.angularjs.org/api/ng.$http有Cache选项.

如何在angularjs中的$ resource中添加类似功能?

Nar*_*etz 59

从1.1.2(commit)开始,所有$ httpConfig选项都直接暴露在$ resource操作对象中:

return {
  Things: $resource('url/to/:thing', {}, {
    list : {
      method : 'GET',
      cache : true
    }
  })
 };
Run Code Online (Sandbox Code Playgroud)

  • 您可以从$ resource文件(不是核心文件的一部分)中提取相关更改,并将其修补到stable分支中.由于1.1.x分支在我的经验非常稳定,我可以推荐使用它.无论如何,这是问题的一种可能的解决方案,而不是确定的答案. (3认同)
  • 试图在1.1.4中使用这个并没有解决:( (2认同)

asg*_*oth 56

在AngularJs中实现自己的缓存非常简单.只需使用$ cacheFactory:

app.factory('myService', function($resource, $cacheFactory) {
   var cache = $cacheFactory('myService');
   var User = $resource('/user/:userId', {userId:'@id'});

   return {
      getResource: function(userId) {
         var user = cache.get(userId);
         if (!user) {
            user = User.get({userId:userId});
            cache.put(userId, user);   
         }
         return user;
      }
   };
});
Run Code Online (Sandbox Code Playgroud)

  • 实际上,$ resource现在具有内置缓存支持.无需手动完成. (15认同)

Bra*_*mus 24

正如文档所述,$ resource内置了对$ cacheFactory的支持.您可以通过cache每个操作的属性传递它:

cache- {boolean|Cache}- 如果true,$http将使用默认缓存来缓存GET请求,否则如果使用缓存实例构建$cacheFactory,则此缓存将用于缓存.

用法示例:

app.factory('Todos', function($resource, $cacheFactory) {
    var todosCache = $cacheFactory('Todos');
    return $resource(apiBaseUrl + '/todos/:id', {id: '@id'}, {
        'get': { method:'GET', cache: todosCache},
        'query': { method:'GET', cache: todosCache, isArray:true }
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 您应该传递一个Cache实例(使用$ cacheFactory构建)而不是$ cacheFactory本身. (2认同)

Iai*_*zor 6

这似乎没有在这里提到,但您也可以覆盖默认方法.

app.factory("List", ["$resource", function($resource) {
    return $resource("./lists/:path/:action.json", {}, {
        get: {
            method: "GET",
            cache: true
        }
    });
}]);
Run Code Online (Sandbox Code Playgroud)


Jea*_* F. 6

您还可以为$ http设置默认缓存,从而为基于它的$ resource设置默认缓存.

我的设置具有出色的角度缓存,允许LocalStorage并符合$ cacheFactory:

app.run(function($http, DSCacheFactory) {

    DSCacheFactory('defaultCache', {
        deleteOnExpire: 'aggressive',
        storageMode: 'localStorage' 
    });

    $http.defaults.cache = DSCacheFactory.get('defaultCache');
});
Run Code Online (Sandbox Code Playgroud)