[英]AngularJS global $http timeout
We can manually set timeout to each $http
via $http.get('url', {timeout: 5000});
我们可以通过$http.get('url', {timeout: 5000});
手动为每个$http
设置超时$http.get('url', {timeout: 5000});
Is it possible to set a global $http
timeout once and it will apply to the whole application? 是否可以设置一次全局$http
超时,它将应用于整个应用程序?
You can use request http interceptor. 您可以使用请求http拦截器。 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: 然后在.config中注入$ httpProvider并执行以下操作:
$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_defaults
in every controller were you are using $http
. 在这里你可以看到更简单的方法在每个控制器上面注入http_defaults
,你使用的是$http
。 And set all default properties of http request. 并设置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);
};
});
I would suggest to use first option. 我建议使用第一个选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.