【问题标题】:How to abort a request in a http-interceptor?如何中止 http 拦截器中的请求?
【发布时间】:2014-09-25 18:50:47
【问题描述】:

在一个应用程序中,我有以下 api 的 url 结构:

// public
public/url-xyz

// private
dashboard/url-xyz

了解这一点并尝试保存不必要的请求:取消请求的最佳方法是什么?到目前为止我尝试过的是:

angular.module('mymod').factory('httpInterceptors', function ($injector, $q, httpBuffer)
{

    return {
        request: function (config)
        {
            var url = config.url;
            if (url.match('/dashboard/')) {
                    // immediately cancel request
                    var canceler = $q.defer();
                    config.timeout = canceler.promise;
                    canceler.reject(config);

                    // logout and go to login-page immediately
                    // ...                       
            }

            // request config or an empty promise
            return config || $q.when(config);
        }       
    };
});

但这可能会导致$ressource 出现问题,因为它需要一个数组并获取一个对象作为响应,如果它的请求被这样取消的话。

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

你应该可以返回$q.reject([reason])

angular.module('mymod').factory('httpInterceptors', function ($injector, $q, httpBuffer)
{

    return {
        request: function (config)
        {
            var url = config.url;
            if (url.match('/dashboard/')) {
                    // immediately cancel request
                    return $q.reject(config);

                    // logout and go to login-page immediately
                    // ...                       
            }

            // request config or an empty promise
            return config || $q.when(config);
        }       
    };
});

【讨论】:

  • 这可行,但也使用拦截器破坏了许多第三方模块(例如,restangular、各种全局加载微调器、http-authentication 模块等)
  • 是的,拦截器会拦截所有的$http请求,如果你拒绝它们会产生影响。有些工具不够智能,无法查找被拒绝的 Promise,并且总是假设请求会得到成功的响应。
猜你喜欢
  • 1970-01-01
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 2014-10-17
  • 2017-02-28
  • 1970-01-01
相关资源
最近更新 更多