在angularjs中等待REST服务响应时检查浏览器超时

时间:2017-03-17 18:02:45

标签: angularjs rest connection-timeout

我正在调用PUT REST服务,如果浏览器端出现60秒的超时而不是服务器端,那么我必须显示一个popover。 如何在AngularJS中检查浏览器超时? (REST服务响应不是错误,它只是在浏览器端超时。)

cancelData: function(cancelData2) { //code
    return $http({ method: 'PUT', 
            data: cancelData2,
            url: endpointURL,
            headers: {'Content-Type': 'something',
                      'Accept' : 'something'},
            timeout: 60000 });
}

3 个答案:

答案 0 :(得分:1)

角度配置中的

可以根据错误代码将响应时间设置为$httpProvider

如果您想要所有http调用的全局解决方法,请使用此

.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.timeout = 6000;
}]);

请注意,当超时响应时,将在promise的错误部分输入,因此您需要在那里添加弹出窗口。

如果您想将其设置为单独的http请求,请使用此方法

 $http.get("/home", { 
   timeout: 6000 
 })
   .success(success)
   .error(error);

答案 1 :(得分:0)

对于angular $ http,当API超时时,在$ http的错误处理函数中获得状态-1。但是,如果要从单个句柄处理所有网络错误,可以使用角度httpInterceptors。示例httpInterceptors

angular.module('myApp')
.config(['$httpProvider', function($httpProvider) {

    $httpProvider.interceptors.push('timeoutHttpIntercept');

    $httpProvider.interceptors.push(['$q', '$rootScope', '$location',
        function ($q, $rootScope, $location) {
       return {
           'request': function (config) {
                return config;
           },
           'response': function (config) {
                return config;
           },
           'responseError': function (response) {
                return $q.reject(response);
           }
       };
    }]);
}])

responseError收到所有$ http错误。你甚至可以在这里提到自定义超时。只需将timeoutHttpIntercept定义为这样的工厂:

.factory('timeoutHttpIntercept', ['CONSTANTS', 'EMAIL_SERVER_URL', function (CONSTANTS, EMAIL_SERVER_URL) {
    return {
        'request': function (config) {
            config.timeout = 20000;
            return config;
        }
    };
}]);

答案 2 :(得分:0)

你能试试吗?

function timedHttp(delay) {
    var isTimeout = {value: false};
    var promise = $http.get('someUri').then(function(data){
        if(!isTimeout.value) {
          timerId.cancel();
            $scope.yourDataModal = data;
        }
    });
    var timerId = $timeout(function(){
        isTimeout.value = true;
        showTimeoutPopup();
    }, delay);
}