【问题标题】:Angular 1.5 timeout using a HttpInterceptor使用 HttpInterceptor 的 Angular 1.5 超时
【发布时间】:2017-04-11 12:08:34
【问题描述】:

全部,

我正在尝试设置一个全局 httpInterceptor 以在出现客户端超时而不是服务器超时时显示自定义弹出消息。我找到了这篇文章:Angular $http : setting a promise on the 'timeout' config,并将其转换为 httpInterceptor,但它没有按预期工作并且有一些奇怪的行为。

 $provide.factory('timeoutHttpInterceptor', function ($q, $translate, $injector) {

        var timeout = $q.defer();

        var timedOut = false;

        setTimeout(function () {
            timedOut = true;
            timeout.resolve();
        }, 10000);
        return {
            request: function (config) {
                config.timeout = timeout.promise;
                return config;
            },
            response: function(response) {
                return response;
            },
            responseError: function (config) {
                if(timedOut) {
                    var toastr = $injector.get('toastr');
                    toastr.custom('network', $translate('title'), $translate('label'), { timeOut: 5000000000000, closeButton: true, closeHtml: '<button></button>' });
                    return $q.reject({
                        error: 'timeout',
                        message: 'Request took longer than 1 second(s).'
                    });
                }
            },
        };
    });

【问题讨论】:

    标签: javascript angularjs timeout


    【解决方案1】:

    您可以使用$timeout 服务返回一个承诺并将其分配给config.timeout。看看下面的代码。

    .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);
          }
        };
    

    这是完整的工作示例:http://jsfiddle.net/2g1y4bk9/

    【讨论】:

    • 非常感谢您的回答,我实现了它并且它有效,非常有用且超级方便的 jsFiddle。我找了很长时间,但找不到 httpInterceptor 的确切实现,所以现在其他人希望可以。
    • 实施后,我们在使用基于 Selenium 的量角器测试时发现了一些问题。我们还需要释放对象以使这些测试再次工作。量角器相关问题:stackoverflow.com/questions/26299173/… 添加: response: function(response) { $timeout.cancel(response.config.timeout);返回响应; },
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    相关资源
    最近更新 更多