在angularjs拦截器中停止请求 [英] Stop request in angularjs interceptor

查看:32
本文介绍了在angularjs拦截器中停止请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Angularjs 拦截器中停止请求.

How can I stop a request in Angularjs interceptor.

有没有办法做到这一点?

Is there any way to do that?

我尝试使用承诺并发送拒绝而不是解决!

I tried using promises and sending reject instead of resolve !

.factory('connectionInterceptor', ['$q', '$timeout',
   function($q, $timeout) {
    var connectionInterceptor = {
        request: function(config) {
            var q = $q.defer();
            $timeout(function() {
                q.reject();
            }, 2000)
            return q.promise;
            // return config;
        }
    }
    return connectionInterceptor;
  }
])
.config(function($httpProvider) {
   $httpProvider.interceptors.push('connectionInterceptor');
});

推荐答案

我最终使用以下 angular Interceptor 绕过了 angular XHR 调用:

I ended up bypassing angular XHR call with the following angular Interceptor:

function HttpSessionExpiredInterceptor(sessionService) {
    return {
        request: function(config) {
            if (sessionService.hasExpired()) {
                /* Avoid any other XHR call. Trick angular into thinking it's a GET request.
                 * This way the caching mechanism can kick in and bypass the XHR call.
                 * We return an empty response because, at this point, we do not care about the
                 * behaviour of the app. */
                if (_.startsWith(config.url, '/your-app-base-path/')) {
                    config.method = 'GET';
                    config.cache = {
                        get: function() {
                            return null;
                        }
                    };
                }
            }

            return config;
        }
    };
}

这样,任何请求,POST,PUT,...都被转换为 GET,这样缓存机制就可以角度使用.此时,您可以使用自己的缓存机制,在我的情况下,当 session过期了,我不再关心返回什么了.

This way, any request, POST, PUT, ... is transformed as a GET so that the caching mechanism can be used by angular. At this point, you can use your own caching mechanism, in my case, when session expires, I do not care anymore about what to return.

这篇关于在angularjs拦截器中停止请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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