Angular js - 缓存rootScope参数及其值

its*_*sme 5 javascript caching angularjs rootscope

嘿我如何缓存x时间这个我通过$ http($ rootScope.config.app_genres)设置的简单对象?

 $http.get($rootScope.config.app_ws+'get/genres',{},{cache:true}).success(function(response) {
    $rootScope.config.app_genres =  response;
  });
Run Code Online (Sandbox Code Playgroud)

我只想缓存它,以便每次http请求都不重复

sir*_*rhc 4

正如$http 文档中所述,您可以通过缓存配置选项提供自己的缓存对象实例。

这是$cacheFactory我重写该put方法的地方,以便在之后清除缓存TIMEOUT。请注意,这仅适用于一个 URL。我将把这个计时器缓存对象设为通用作为你的练习。

function Ctrl($scope, $http, $cacheFactory, $timeout) {
  var timedCache = $cacheFactory('myCache'),
      TIMEOUT = 5000,
      cacheTimer = null;

  timedCache._put = timedCache.put;
  timedCache.put = function (key, val) {
    console.log('caching', key);

    $timeout.cancel(cacheTimer);
    cacheTimer = $timeout(function () {
      console.log('clearing cache for', key);
      timedCache.remove(key);
    }, TIMEOUT, false);

    timedCache._put(key, val);
  };

  $scope.request = function () {
    $http.get('/echo/json', {
      cache: timedCache
    })
    .success(function (data) {
      console.log('received', data);
    });
  };
}
Run Code Online (Sandbox Code Playgroud)

这是这项工作的小提琴:http://jsfiddle.net/sirhc/jvLPX/