加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 使用$http拦截器取消请求?

发布时间:2020-12-17 09:26:55 所属栏目:安全 来源:网络整理
导读:我试图找出是否可以使用$http拦截器在甚至发生之前取消请求. There is a button that triggers a request but if the user double-clicks it I do not want the same request to get triggered twice. 现在,我意识到有几种方法可以解决这个问题,而且我们已经
我试图找出是否可以使用$http拦截器在甚至发生之前取消请求.

There is a button that triggers a request but if the user double-clicks it I do not want the same request to get triggered twice.

现在,我意识到有几种方法可以解决这个问题,而且我们已经有了一个工作的解决方案,我们把$http包裹在一个服务中,跟踪当前正在等待的请求,并且用相同的方法,url和数据简单地忽略了新的请求.

基本上这是我试图用拦截器的行为:

factory('httpService',['$http',function($http) {

    var pendingCalls = {};

    var createKey = function(url,data,method) {
        return method + url + JSON.stringify(data);
    };

    var send = function(url,method) {
        var key = createKey(url,method);
        if (pendingCalls[key]) {
            return pendingCalls[key];
        }
        var promise = $http({
            method: method,url: url,data: data
        });
        pendingCalls[key] = promise;
        promise.finally(function() {
            delete pendingCalls[key];
        });
        return promise;
    };

    return {
        post: function(url,data) {
            return send(url,'POST');
        }
    }

}])

当我看到$http拦截器的API时,似乎不是一种实现这一点的方法.我可以访问配置对象,但这是关于它.

我试图超越可以在这里使用拦截器的边界,还是有办法呢?

根据 $http documentation,您可以从请求拦截器返回自己的配置.

尝试这样的东西:

config(function($httpProvider) {
    var cache = {};

    $httpProvider.interceptors.push(function() {
        return {
            response : function(config) {
                var key = createKey(config);
                var cached = cache[key];
                return cached ? cached : cached[key];    
            }
        }
    });
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读