最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS global $http timeout - Stack Overflow

programmeradmin6浏览0评论

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?

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?

Share Improve this question asked Oct 24, 2015 at 8:44 user1995781user1995781 19.5k45 gold badges139 silver badges241 bronze badges 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 – Jony-Y Commented Oct 24, 2015 at 8:49
  • @Jony-Y Thanks a lot for your ment. It would be nice if you could show an example how your suggestion can be done. – user1995781 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 – Jony-Y Commented Nov 3, 2015 at 9:34
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论