2014-12-03 76 views
10

我正在角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); 
      }); 

有没有什么办法让我可以显示用户,如果连接超时。 有什么办法可以在一个地方配置它吗?

回答

19

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

// 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); 
      } 
     } 
    }) 
}) 
+0

嗨,我得到了拒绝。状态== 0当请求超时,并且其他网络错误状态也是0 – Raniys 2017-05-09 05:51:05

+2

使用角度1.5.11我得到状态码-1,任何想法在哪里可以找到有关此值的官方文档? – Rachmaninoff 2017-05-10 11:07:12

1

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

+5

其更好地给一些说明和详细信息,提供链接。这样在链接不工作的情况下会有帮助。 – 2014-12-03 14:37:17

+1

这不是一个好例子,因为在调用者代码中设置timedOut,但仍不知道如何检测何时发生真正的http超时。 – user3285954 2015-05-27 15:04:49

+1

这是一个很好的答案。超时角正在寻找始终指的是调用者代码,所以我不知道@ user3285954在说什么。此示例演示如何使用promise作为超时值,您可以在其中插入额外的数据以跟踪哪个超时被触发。尼斯。 – JoshuaDavid 2016-03-16 18:10:59

-2

你只需要检查响应状态,这就是它:

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

}); 

对于全局HTTP超时,看看这个answer

+1

这不是一个好的答案。你从哪里得到408?您不能假定超时会导致状态被传递,即状态可能为0. – JoshuaDavid 2016-03-16 18:06:59

+1

这是不正确的答案。状态码不会等于408. – 2016-03-29 23:20:36

1

你可以使用角拦截器来实现这一点。

$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); 
    }); 
    }; 
}]); 
}]); 

More info see this link