我怎样才能运行一些代码在角度的所有$ http呼叫

我怎样才能运行一些代码在角度的所有$ http呼叫

问题描述:

我想检查用户是否在使用角度应用$http拨打电话之前是否online作为后备我将得到cached data如果网络不可用。

有没有像before回拨的任何选项$http确实运行此检查?

或者,也许来解决这个任何其他方式,我有localstorage

+0

您可以添加[拦截]推动这个拦截到$ httpProvider.interceptors(https://docs.angularjs.org/api/ng/service/$ http#拦截器) –

+0

好的,所以没有选择$ http库我想,我必须在拦截器中做到这一点,它有,然后,赶上,最后,没有回调之前 – Saqueib

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

可以在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'); 
     . 
     . 

});