AngularJs에서 글로벌 http 시간 제한을 설정하는 방법
매번 시간 제한을 설정할 수 있다는 것을 알고 있습니다.
$http.get('path/to/service', {timeout: 5000});
...하지만 내 코드를 DRY로 유지하기 위해 전역 시간 제한을 설정하고 싶습니다.
업데이트 됨 : $ http는 httpProvider에서 설정 한 시간 제한에 대한 기본 설정을 따르지 않습니다 (주석 참조). 가능한 해결 방법 : https://gist.github.com/adnan-i/5014277
원래 답변 :
angular.module('MyApp', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.timeout = 5000;
}]);
이것은 bleeding-edge angular.js (git master 4ae46814ff로 테스트 됨)에서 가능합니다.
요청 http 인터셉터를 사용할 수 있습니다. 이렇게.
angular.module('yourapp')
.factory('timeoutHttpIntercept', function ($rootScope, $q) {
return {
'request': function(config) {
config.timeout = 10000;
return config;
}
};
});
그런 다음 .config에서 $ httpProvider를 주입하고 다음을 수행하십시오.
$httpProvider.interceptors.push('timeoutHttpIntercept');
게시물과 업데이트에 감사드립니다 !!
을 (를) 위해 특별히이 문제를 조사하면서 $resource
찾은 내용에 대해 자세히 설명하겠다고 생각했습니다.
- 이 문제는 추적기에 기록되었으며 angular 1.1.5에서는 timeout 속성을
$http
요청 에 전달하기위한 지원이 있습니다 .
https://github.com/angular/angular.js/issues/2190 http://code.angularjs.org/1.1.5/docs/api/ngResource.$resource
이전 버전의 경우, 특히 angular 1.0.6을 사용하고 있습니다. 396 행에서 angular-resource.js의 소스 파일을 편집
$http
할 수 있습니다. 모든 사용자에 대해 timeout 속성을 직접 추가 할 수 있는 호출을 찾을 수 있습니다. 자원 요청.언급되지 않았고 Stewie의 솔루션을 테스트해야했기 때문에 시간 초과가 발생했을 때 오류와 중단 / 시간 초과를 구분하는 방법은 'status'인수를 확인하는 것입니다. 다음
0
과 같이 대신 시간 초과에 대해 반환 됩니다404
.$http.get("/home", { timeout: 100 }) .error(function(data, status, headers, config){ console.log(status) }
시간 제한을 전역 적으로 설정하는 것과 반대로 사용해야하는 경우가 거의
$timeout
없기 때문에 다음과 같이 함수 에서 요청을 래핑합니다 .//errorHandler gets called wether it's a timeout or resource call fails var t = $timeout(errorHandler, 5000); myResource.$get( successHandler, errorHandler ) function successHandler(data){ $timeout.cancel(t); //do something with data... } function errorHandler(data){ //custom error handle code }
나는 동일한 요구 사항을 가지고 있으며 AngularJS 1.0.7을 사용하고 있습니다. 위의 솔루션 중 어느 것도 나에게 적합하지 않은 것 같기 때문에 아래 코드를 생각해 냈습니다 (시간 제한이 한곳에서 전역 적이기를 원한다는 의미에서 가능합니다). 기본적으로, 원래의 $ HTTP를 방법을 마스킹 및 추가하고있어 timeout
각각의 $http
요청 및 기타 바로 가기 방법 등의 오버라이드 (override) get
, post
... 그래서 그들은 마스크 새로운를 사용할 것이라는 점을 $http
.
아래 코드에 대한 JSFiddle :
/**
* @name ngx$httpTimeoutModule
* @description Decorates AngularJS $http service to set timeout for each
* Ajax request.
*
* Implementation notes: replace this with correct approach, once migrated to Angular 1.1.5+
*
* @author Manikanta G
*/
;(function () {
'use strict';
var ngx$httpTimeoutModule = angular.module('ngx$httpTimeoutModule', []);
ngx$httpTimeoutModule.provider('ngx$httpTimeout', function () {
var self = this;
this.config = {
timeout: 1000 // default - 1 sec, in millis
};
this.$get = function () {
return {
config: self.config
};
};
});
/**
* AngularJS $http service decorator to add timeout
*/
ngx$httpTimeoutModule.config(['$provide', function($provide) {
// configure $http provider to convert 'PUT', 'DELETE' methods to 'POST' requests
$provide.decorator('$http', ['$delegate', 'ngx$httpTimeout', function($http, ngx$httpTimeout) {
// create function which overrides $http function
var _$http = $http;
$http = function (config) {
config.timeout = ngx$httpTimeout.config.timeout;
return _$http(config);
};
$http.pendingRequests = _$http.pendingRequests;
$http.defaults = _$http.defaults;
// code copied from angular.js $HttpProvider function
createShortMethods('get', 'delete', 'head', 'jsonp');
createShortMethodsWithData('post', 'put');
function createShortMethods(names) {
angular.forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(angular.extend(config || {}, {
method : name,
url : url
}));
};
});
}
function createShortMethodsWithData(name) {
angular.forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(angular.extend(config || {}, {
method : name,
url : url,
data : data
}));
};
});
}
return $http;
}]);
}]);
})();
위 모듈에 대한 종속성을 추가하고 ngx$httpTimeoutProvider
아래와 같이 구성하여 제한 시간을 구성하십시오 .
angular.module('App', ['ngx$httpTimeoutModule']).config([ 'ngx$httpTimeoutProvider', function(ngx$httpTimeoutProvider) {
// config timeout for $http requests
ngx$httpTimeoutProvider.config.timeout = 300000; // 5min (5 min * 60 sec * 1000 millis)
} ]);
참고 URL : https://stackoverflow.com/questions/15015416/how-to-set-a-global-http-timeout-in-angularjs
'IT TIP' 카테고리의 다른 글
CloudFront의 TTL 0은 무엇에 유용합니까? (0) | 2020.10.18 |
---|---|
grid.arrange를 사용하여 플롯의 변수 목록을 어떻게 정렬합니까? (0) | 2020.10.18 |
size_t 또는 ssize_t를 사용해야합니다. (0) | 2020.10.18 |
pip install numpy 관련 문제-RuntimeError : Broken toolchain : cannot link a simple C program (0) | 2020.10.18 |
블루투스 애플리케이션을 테스트하기 위해 Android 에뮬레이터를 사용하는 방법은 무엇입니까? (0) | 2020.10.18 |