2016-03-04 72 views
1

我想檢查用戶是否在使用角度應用$http撥打電話之前是否online作爲後備我將得到cached data如果網絡不可用。

有沒有像before回撥的任何選項$http確實運行此檢查?

或者,也許來解決這個任何其他方式,我有localstorage

+0

您可以添加[攔截]推動這個攔截到$ httpProvider.interceptors(https://docs.angularjs.org/api/ng/service/$ http#攔截器) –

+0

好的,所以沒有選擇$ http庫我想,我必須在攔截器中做到這一點,它有,然後,趕上,最後,沒有回調之前 – Saqueib

回答

3

network state &緩存你可以只寫你自己的HTTP服務的包裝。

function httpMonkey ($http) { // I like to call all my services 'monkeys'; I find it makes angular more fun 
    function request (args) { 
    // stuff to do before, likely as a promise 
    .then(function() { 
     // the actual http request using $http 
    }) 
    .then(function() { 
     // stuff to do after, perhaps? 
    }); 
    } 

    var service = { request: request }; 
    return service; 
} 

angular 
    .module('example') 
    .factory('HttpMonkey', httpMonkey); 
1

可以在angularJs定製httpInteceptor添加到$ httpProvider服務。
下面是一個例子 - 我創建了一個httpInteceptor,它將在每個$ http調用之前顯示loadingSpinner,並在成功/錯誤後隱藏它。

//Intercepts ALL angular ajax http calls 
app.factory('httpInterceptor', function ($q, $rootScope, $log) { 
    var numLoadings = 0; 
    return { 
     request: function (config) { 
      numLoadings++; 
      // Show loader 
      $('#loadingSpinner').show(); 
      return config || $q.when(config) 
     }, 
     response: function (response) { 
      if ((--numLoadings) === 0) { 
       // Hide loader 
       $('#loadingSpinner').hide(); 
      } 
      return response || $q.when(response); 
     }, 
     responseError: function (response) { 
      if (!(--numLoadings)) { 
       // Hide loader 
       $('#loadingSpinner').hide(); 
      } 
      return $q.reject(response); 
     } 
    }; 
}) 

,然後在app.config-

app.config(function ($routeProvider, $httpProvider) { 
     $httpProvider.interceptors.push('httpInterceptor'); 
     . 
     . 

});