【问题标题】:Angular js interceptor that returns a cached response返回缓存响应的 Angular js 拦截器
【发布时间】:2016-04-26 23:31:05
【问题描述】:

我想制作一个 angularJS 拦截器,当客户端离线时返回缓存响应而不是错误,就好像它不是任何错误一样。

到目前为止,我所做的是制作一个缓存 api 请求的拦截器:

app.factory('httpCachingInterceptor', function ($q, apiCache) {
return {

  'response' : function(response) {
    // cache the api
    if (response.config.url.indexOf('api/') > 0)
      apiCache.addApiCache(response.config.url, response.data);
    return response;
  },

  'responseError' : function(rejection) {
    if (rejection.status == -1) {
      // get the data from apiCache
      // 
      apiCache.getApiCache(rejection.config.url, function(data) {
        // build a new promise and return it as a valid response

      })
    }
    return $q.reject(rejection);
  }

 }
})

我注意到,当我离线时,rejection.status 为 -1,所以我检查是否在离线时发出了请求。

我的问题是如何构建响应? 我应该做出新的承诺还是可以更新拒绝?

【问题讨论】:

    标签: angularjs angular-http-interceptors


    【解决方案1】:

    将被拒绝的承诺转换为已履行的承诺返回 onRejection 处理程序中的值。

    相反,要将已履行的承诺转换为被拒绝的承诺抛出 onFulfilled 处理程序中的值。

    欲了解更多信息,请参阅Angular execution order with $q

    【讨论】:

      【解决方案2】:

      我设法使它像这样工作:

      'responseError' : function(rejection) {
          if (rejection.status == -1) {
            // get the data from apiCache
            var deferred = $q.defer();
      
            apiCache.getApiCache(rejection.config.url, function(err, data) {
              if (err || !data) {
                return deferred.reject(rejection);
              }
              rejection.data = data;
              rejection.status = 200;
              deferred.resolve(rejection);
              console.log("Resolve promise with ", rejection);
            })
      
            return deferred.promise;
          }
          return $q.reject(rejection);
       }
      

      所以我做了一个新的承诺,并用缓存中的新数据修改了我得到的拒绝。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-14
        • 2018-06-27
        • 2015-11-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多