2
我們可以通過$http.get('url', {timeout: 5000});
手動設置每個$http
的超時時間是否可以設置全局$http
超時一次,它將應用於整個應用程序?
我們可以通過$http.get('url', {timeout: 5000});
手動設置每個$http
的超時時間是否可以設置全局$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);
};
});
我會建議使用第一個選項。
您是否知道$ http服務的默認超時值?還是沒有默認超時(等待)? – demaniak
如果你在一個服務中包裝你的http調用,那麼是的。或用戶某種$ http攔截服務,也可以做...如果你需要示例讓我知道 –
@ Jony-Y非常感謝您的評論。如果你能夠舉一個例子說明你的建議是否可以完成,那將會很好。 – user1995781
非常像@NetSou在答案中顯示的...只需將您的$超時添加到您的帳號或您想要它執行的任何操作 –