AngularJs에서 글로벌http 타임아웃을 설정하는 방법
매번 타임아웃을 설정할 수 있습니다.
$http.get('path/to/service', {timeout: 5000});
... 단, 코드를 DRY 상태로 유지하도록 글로벌타임아웃을 설정합니다.
이것은 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');
업데이트: $http는 http Provider에서 설정한 타임아웃 기본 설정을 따르지 않습니다(댓글 참조).생각할 수 있는 회피책:https://gist.github.com/adnan-i/5014277
원답:
angular.module('MyApp', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.timeout = 5000;
}]);
투고와 업데이트 감사합니다!!
이 문제에 대한 조사에서는 특히$resource
제가 발견한 것에 대해 자세히 말씀드리겠습니다.
- 이 문제는 트래커에 기록되었으며 각도 1.1.5에서는 타임아웃 속성을 통해
$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
모든 리소스 요청에 대해 시간 초과 속성을 직접 추가할 수 있습니다.언급되지 않았고 Stewie의 솔루션을 테스트해야 했기 때문에 타임아웃이 발생했을 때 오류와 abort/timeout을 구분하는 방법은 '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
요구 및 기타 숏컷 메서드 덮어쓰기 등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
'sourcetip' 카테고리의 다른 글
AngularJS 라우팅 대소문자의 구별 (0) | 2023.03.04 |
---|---|
AngularJS: 숨김 양식 필드의 유효성을 검사하지 않습니다. (0) | 2023.03.04 |
Oracle 11g Express Edition for Windows 64bit? (0) | 2023.03.04 |
H2 데이터베이스 콘솔 스프링 부팅 로드가 X-Frame-Options에 의해 거부되었습니다. (0) | 2023.03.04 |
대응: 스테이트리스 기능 컴포넌트의 PropType (0) | 2023.03.04 |