【问题标题】:AngularJS Interceptors - Modify the response data to cached dataAngularJS 拦截器 - 将响应数据修改为缓存数据
【发布时间】:2018-07-20 07:03:06
【问题描述】:

我想创建一个带有 etags 和角度拦截器的缓存解决方案。 一切正常,但我无法返回缓存的数据。 我想用缓存的数据覆盖304 Not Modified 响应。

      'responseError': function(rejection) {

          if(rejection.status === 304){
              var response = {};

              var url = rejection.config.url;
              var params = rejection.config.params || {};
              var etagKey = url+'.'+JSON.stringify(params);
              var storedValue = $localStorage['ETag-Cache'+etagKey] || '{}';
              var cachedObj = JSON.parse(storedValue);

              console.log('CACHED ETag-Cache'+etagKey,cachedObj.response);

              //I'd like to return with the cached data here but this doesn't work
              return cachedObj.response;

          }

          return $q.reject(rejection);
      }

下面的示例请求

      $http.get('/api/bigdata', {


    }).then(function(resp){
       //I'd like to get the cached data in the resp variable
    });

【问题讨论】:

  • 304 响应由浏览器自动处理。不会传递给 $http 服务。
  • 我在 $http.then(resp) 中得到了某种响应(承诺),所以理论上它可以工作:) 如果我用 $http.cache(resp) 捕获 304 响应) 我可以处理这个,但我不想在整个项目的每个文件中添加每个请求,在拦截器中处理这个会很棒。

标签: angularjs caching angular-http-interceptors etags


【解决方案1】:

我没有找到解决方案,但我有一个解决方法。 由于304 错误状态的问题,我将返回一个状态代码200,而不是一个自定义标头:Not-Modified = 1 和一个空响应,然后我在拦截器中处理它。

Laravel ETag MiddleWare 中的伪代码

        if ($requestEtag && $requestEtag[0] == $etag) {
            $response->setStatusCode(200);
            $response->header('Not-Modified', true);
            $response->setContent('{"status":"Not-Modified"}');
        }

AngularJS 拦截器响应处理程序:

        //Etag Handler
        var url = res.config.url;
        var params = res.config.params || {};
        var etag = res.headers().etag;
        var etagKey = url+'.'+JSON.stringify(params);
        var EtagVal = JSON.stringify(
            {
                'etag':etag,
                'url':url,
                'params':params,
                'response':res.data
            });


        //If Not-Modified header is true
        if(res.headers()['not-modified'] == "1"){
            var storedValue = $localStorage['ETag-Cache'+etagKey] || '{}';
            var cachedObj = JSON.parse(storedValue);

            console.log('CACHED ETag-Cache'+etagKey,cachedObj.response);
            res.data = cachedObj.response;
            return res || $q.when(res);
        }

这样我可以在$http.then(response) 中获取缓存值,而不是从服务器下载整个数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多