【问题标题】:Angular js - cache a rootScope param and it's valueAngular js - 缓存一个 rootScope 参数及其值
【发布时间】:2014-02-18 09:32:03
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript angularjs caching rootscope


    【解决方案1】:

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

    这是一个$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);
        });
      };
    }
    

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

    【讨论】:

      【解决方案2】:

      你好,(希望 Angular 内置了一些东西,其他人可以添加但是)

      我想我们可以将它分配给一个新变量

      $rootScope.dataCache = $rootScope.data;
      
      $rootScope.cacheTimer = 50000; 
      

      您的网站应用程序始终从 $rootScope.dataCache 读取数据,并在 CacheTimer 已过时检查和/或自动更新,以调用服务器端并重新分配。

      ?

      【讨论】:

      • 所以 dataCache 和 cacheTimer 是原生的? :P
      • 不,它们听起来可能是,不,只是您选择的常规变量名称。
      • 谢谢,您能否为社区提供一个工作示例? :)
      • 今天有足够的时间,也许吧。让我知道这是否没有帮助,如果有帮助,我将删除它并留下“未回答”的问题,或者发布您使用此原则的程度。
      【解决方案3】:

      我用这段代码缓存模板

      $http.get(/*URL*/, {cache: $templateCache})
          .success(function () { ... })
          .error(function () { ... });
      

      但也许这个会是你想做的更多 https://coderwall.com/p/40axlq

      【讨论】:

        【解决方案4】:

        您可以根据需要使用缓存清除。假设您只想缓存 x 秒。您添加了一个带有值的缓存破坏查询参数

        Math.floor(new Date().getTime() / (x * 1000))

        请求看起来像

        $http.get(url,{cacheBuster: Math.floor(new Date().getTime() / (x * 1000))},{cache:true})
        

        【讨论】:

          猜你喜欢
          • 2013-04-26
          • 1970-01-01
          • 2020-01-26
          • 1970-01-01
          • 2019-06-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多