2

We can manually set timeout to each $http via $http.get('url', {timeout: 5000}); Is it possible to set a global $http timeout once and it will apply to the whole application?

3
  • if you wrap your http calls in a service which does that then yes. or user some sort of $http interceptor service, also could be done... if you need examples let me know Commented Oct 24, 2015 at 8:49
  • @Jony-Y Thanks a lot for your comment. It would be nice if you could show an example how your suggestion can be done. Commented Nov 3, 2015 at 6:05
  • pretty much like @NetSou showed in the answer... just add your $timeout there or what ever you want it to do Commented Nov 3, 2015 at 9:34

1 Answer 1

8

You can use request http interceptor. Like this.

angular.module('myapp')
  .factory('timeoutHttpInterceptor', function () {
    return {
      'request': function(config) {
        config.timeout = 10000;
        return config;
      }
    };
 });

And then in .config inject $httpProvider and do this:

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

OR You can do like this also:

// this custom config could actually be a part of a more general app-level config
  // so that you need to inject only one global config
  myApp.value('http_defaults', {
    timeout: 150
  });

Here you can see more simple way Inject above http_defaultsin every controller were you are using $http. And set all default properties of http request.

myApp.controller('myCtrl', function ($scope, $http, http_defaults) {

  // in case you need to change the default values for this specific request
      // angular.extend(http_defaults, {timeout: 300});

      $http.get("/xyz", http_defaults)
        .success(success)
        .error(error);
    };
});

You can refer this

I would suggest to use first option.

Sign up to request clarification or add additional context in comments.

1 Comment

would you perhaps know what the default timeout is for $http service? Or is there no default timeout (wait for ever)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.