首页 > 解决方案 > AngularJS 拦截器 - 将响应数据修改为缓存数据

问题描述

我想用 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
    });

标签: angularjscachingangular-http-interceptorsetags

解决方案


我还没有找到解决方案,但我有一个解决方法。由于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)而不是从服务器下载整个数据。


推荐阅读