【问题标题】:Custom cache for HTTP requestsHTTP 请求的自定义缓存
【发布时间】:2017-08-07 08:08:27
【问题描述】:

我想缓存响应 [i.e.解析的 JSON 响应] HTTP 请求而不是响应本身。我的数据很大并且经过 gzip 压缩,因此解压缩它实际上会对性能造成相当大的影响,因此我想存储原始数据本身。

目前我正在使用 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;
    }
  };
}])

【问题讨论】:

  • 克里斯有什么反馈吗?

标签: angularjs http caching


【解决方案1】:

我更愿意将其注入您的服务中,并使您的工厂仅处理接收/缓存的数据。这次我只为你创建了一个服务,它包含 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();
        }
    };
}]);

【讨论】:

    【解决方案2】:

    在请求选项中添加{cache: true} 就足够了。

    here

    $http.get('some/url', {cache: true})
    .then( ({data}) => data)
    

    【讨论】:

      猜你喜欢
      • 2019-11-08
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 2014-08-08
      • 2013-05-31
      • 2012-04-05
      • 2016-06-29
      相关资源
      最近更新 更多