2017-03-16 126 views
1

我想缓存响应[即解析JSON响应]的HTTP请求,而不是响应本身。我的数据很大并且是gzip,所以实际上有一个公平的性能解压缩,所以想存储原始数据本身。HTTP请求的自定义缓存

目前我正在使用HTTP拦截器进行缓存,并使用TimeToLive机制described here以及AngularJS内置的$cacheFactory

那么,如何使用拦截器停止HTTP请求并返回我自己的响应。注意我仍然计划使用$cacheFactory,我只是管理自己的数据。

.factory('cacheInterceptor', ['$cacheFactory', function($cacheFactory) { 
    return { 
    request: function(config) { 
     if (config.cache) { 
     // if we have stored this request, return it, else let the request happen naturally and cache after 

     // Things I don't know: 
     // How to return existing cache data and prevent the reqeust from happening 
     // Cache the data I get back from a HTTP request 
     } 

     return config; 
    } 
    }; 
}]) 
+0

有没有反馈Chris? – lin

回答

1

我愿意将此注入到您的服务中,并使您的工厂只处理recived/cached的数据。这次我只为你创建了一个服务,它保存了HTTP/Cache切换的逻辑。我认为你将能够创建一个工厂来处理你自己的数据/状态。

.service('getService', ['$cacheFactory', '$http', '$q', function($cacheFactory, $http, $q) { 
    return { 
     request: function() { 
      function getData() { 
       var deferred = $q.defer(); 
       if (angular.isUndefined($cacheFactory.get('getServiceData'))) { 
        $http({ 
         'method': 'GET', 
         'url': 'someUrl' 
        }).then(function (result) { 
         $cacheFactory.put('getServiceData', result.data); 
         deferred.resolve(result.data); 
        }); 
       } else { 
        deferred.resolve($cacheFactory.get('getServiceData')); 
       } 
      } 

      return getData(); 
     }, 
     flush: function() { 
      $cacheFactory.remove('getServiceData'); 
     }, 
     refresh: function() { 
      this.flush(); 
      return this.refresh(); 
     } 
    }; 
}]);