angularjs – 使用$http拦截器重试失败的请求

前端之家收集整理的这篇文章主要介绍了angularjs – 使用$http拦截器重试失败的请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的webapp正在谈论的API有时会重载,如果无法处理请求,则会发送500内部服务器错误.

我的Web应用程序可以发送100个不同的请求,所以如果我每个单独执行重试,这将花费我几个小时的打字.

我已经在使用$httpProvider拦截器了,这里是(简化的)

  1. $httpProvider.interceptors.push(function ($q) {
  2. return {
  3. responseError: function (response) {
  4. switch (response.status) {
  5. case 401 :
  6. window.location = "/";
  7. alert('Session has expired. Redirecting to login page');
  8. break;
  9. case 500 :
  10. // TODO: retry the request
  11. break;
  12. }
  13. return $q.reject(response);
  14. }
  15. };
  16. });

从服务器获取500个响应代码后,如何重新发送请求?

Angular提供了对$http服务在响应(response.config)中执行请求使用的配置对象的引用.这意味着如果我们可以在拦截器中注入$http服务,我们可以轻松地重新发送请求.因为循环依赖关系,简单的注入$http服务是不可能的,但幸运的是有一个解决方法.

这是一个如何实现一个这样的拦截器的例子.

  1. $httpProvider.interceptors.push(function ($q,$injector) {
  2. var incrementalTimeout = 1000;
  3.  
  4. function retryRequest (httpConfig) {
  5. var $timeout = $injector.get('$timeout');
  6. var thisTimeout = incrementalTimeout;
  7. incrementalTimeout *= 2;
  8. return $timeout(function() {
  9. var $http = $injector.get('$http');
  10. return $http(httpConfig);
  11. },thisTimeout);
  12. };
  13.  
  14. return {
  15. responseError: function (response) {
  16. if (response.status === 500) {
  17. if (incrementalTimeout < 5000) {
  18. return retryRequest(response.config);
  19. }
  20. else {
  21. alert('The remote server seems to be busy at the moment. Please try again in 5 minutes');
  22. }
  23. }
  24. else {
  25. incrementalTimeout = 1000;
  26. }
  27. return $q.reject(response);
  28. }
  29. };
  30. });

Note: In this example implementation the interceptor will retry the request until you receive a response with status that is different than 500. Improvement to this can be adding some timeout before retrying and retrying only once.

猜你在找的Angularjs相关文章