繁体   English   中英

AngularJS全局$ http超时

[英]AngularJS global $http timeout

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

您可以使用请求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);
    };
});

你可以参考这个

我建议使用第一个选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM