Angular 1.5 timeout using a HttpInterceptor

后端 未结 1 1571
夕颜
夕颜 2021-01-21 16:30

All,

i am trying to setup a global httpInterceptor to have a custom popup message when a client timeout appears, not a server one. I found this article: Angular $http :

1条回答
  •  清酒与你
    2021-01-21 17:03

    You can use $timeout service that returns a promise and assign it to config.timeout. Take a look at the code below.

    .factory('timeoutInterceptor', ['$q','$timeout', function($q,$timeout) {
        return {
          request: function(config) {
            //assign a promise with a timeout, and set timedOut flag, no need to trigger $digest, thus false as 3rd param
            config.timeout = $timeout(function(){ config.timedOut = true },2000,false);
            return config;
          },
          responseError :function(rejection) {
            if(rejection.config.timedOut){ //if rejected because of the timeout - show a popup 
                alert('Request took longer than 1 second(s).');
            }
            return $q.reject(rejection);
          }
        };
    

    Here is full working example : http://jsfiddle.net/2g1y4bk9/

    0 讨论(0)
提交回复
热议问题