如何在角度 js $http调用中显示超时错误

How to display timeout error in angular js $http calls?

本文关键字:调用 显示 超时 错误 http js      更新时间:2023-09-26

我正在使用角度js中的$http进行ajax调用。我已经在其中实现了超时。但是我想在连接超时时向用户显示错误消息。以下是代码。

$http({
            method: 'POST',
            url: 'Link to be called',
            data: $.param({ 
                    key:Apikey,
                    id:cpnId
                }),
            timeout : 5000, 
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function(result){
               alert(result);
            }).error(function(data){
              alert(data);
            });

有什么方法可以在连接超时时显示用户。有什么方法可以在一个地方配置它吗?

如果你想在每个

请求的连接超时时做一些事情,你可以使用拦截器(全局超时参数不起作用):

// loading for each http request
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push(function ($rootScope, $q) {
        return {
            request: function (config) {
                config.timeout = 1000;
                return config;
            },
            responseError: function (rejection) {
                switch (rejection.status){
                    case 408 :
                        console.log('connection timed out');
                        break;
                }
                return $q.reject(rejection);
            }
        }
    })
})

试试这个博客页面:http://www.jonhartmann.com/index.cfm/2014/7/23/jsFiddle-Example-Proper-Timeout-Handling-with-AngularJS它有一个完整的角度运行示例,可以解决您的问题。

您可以使用角度拦截器来实现此目的。

$httpProvider.responseInterceptors
.push(['$q', '$injector','$rootScope', function ( $q, $injector,$rootScope) {
 return function (promise) {
    return promise.then(function (response) {
        return response;
    }, function (response) {
        console.log(response); // response status
        return $q.reject(response);
    });
  };
 }]);
}]);

更多信息请参阅此链接

您只需要检查响应状态,就是这样:

}).error(function(data, status, header, config) {
      if (status === 408) {
          console.log("Error - " + status + ", Response Timeout.");
      } 
});

对于全局 HTTP 超时,请查看此答案