Restanglar。从请求拦截器捕获响应

时间:2014-09-12 11:51:11

标签: angularjs restangular

我需要为每个Restangular请求设置超时,如果收到成功响应,则取消它。问题是请求拦截器中的访问响应如何?

1 个答案:

答案 0 :(得分:1)

我是如何解决的:

服务:

angular.module('mmn')
  .factory('serverTimeout', function($timeout, $rootScope) {

    var serverTimeout = {
      request: function(config) {
        config.timeout = $timeout(function() {
          $rootScope.$broadcast('event:serverTimeout');
        }, 30000);

        return config;
      },
      response: function(response) {
        $timeout.cancel(response.config.timeout);
        return response;
      }
    };
    return serverTimeout;
  });

App.config中:

$httpProvider.interceptors.push('serverTimeout');

App.run:

  //watch serverTimeout event
  $rootScope.$on('event:serverTimeout', function(){
    //your handler here
  });