AngularJS全局$ http超时

时间:2015-10-24 08:44:37

标签: javascript angularjs

我们可以通过$http手动设置每个$http.get('url', {timeout: 5000});的超时时间是否可以设置一次全局$http超时,它将适用于整个应用程序?

1 个答案:

答案 0 :(得分:8)

您可以使用请求http拦截器。像这样。

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

然后在.config中注入$ httpProvider并执行此操作:

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

或者您也可以这样做:

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

在这里,您可以看到更简单的方法在您使用http_defaults的每个控制器中注入$http以上。并设置http请求的所有默认属性。

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

我建议使用第一个选项。