2016-04-26 83 views
0

我想做一個angularJS攔截器,當客戶端離線返回而不是錯誤的緩存響應,就好像它沒有任何錯誤。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所以這是當我檢查,如果請求是在離線時完成的。

我的問題是我如何構建響應? 我應該作出新的承諾還是可以更新拒絕?

回答

0

我設法使它像這樣的工作:

'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); 
} 

所以我做了一個新的承諾,修改我從緩存中的新數據得到了抑制。

0

將拒絕的承諾轉換爲履行的承諾返回處理器中的值onRejection

相反,將滿足承諾轉換爲拒絕承諾丟棄處理器的值爲onFulfilled

欲瞭解更多信息,請參閱Angular execution order with $q