Search code examples
angularjsrestangular

Restanglar. Catch response from request interceptor


I need to set timeout to every Restangular request and cancel it if success response received. The question is how access response in request interceptor?


Solution

  • How I solved it:

    Service:

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