使用HttpInterceptor进行Angular 1.5超时 [英] Angular 1.5 timeout using a HttpInterceptor

查看:95
本文介绍了使用HttpInterceptor进行Angular 1.5超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部,

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

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 : setting a promise on the 'timeout' config , and converted it into a httpInterceptor, but it does not work as expected and has some weird behavior.

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


推荐答案

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

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

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

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

这篇关于使用HttpInterceptor进行Angular 1.5超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆