2014-09-25 263 views
0

在应用程序中我对API以下网址结构:如何在http拦截器中取消请求?

// 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问题。

+0

有趣的是我发现通过谷歌同样的问题,但我无法通过stacoverflow搜索找到它,我因而无法以纪念我作为一个重复的问题: http://stackoverflow.com/questions/22090792/cancelling-a-request-with-a-http-interceptor – 2014-09-25 19:02:23

+0

教程在这里http://www.freakyjolly.com/how-to-cancel-http-requests-in -angularjs-app/ – 2017-08-13 11:59:12

回答

2

你应该能够返回$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); 
     }  
    }; 
}); 
+1

这可以工作,但是使用拦截器也会破坏很多第三方模块(例如,restangular,各种全局加载spinners,http认证模块等)。 – 2014-09-25 19:28:12

+1

是的,拦截器将会拦截所有'$ http'请求,如果拒绝它们,将会产生影响。有些工具不够聪明,无法查找被拒绝的承诺,并始终认为请求会得到成功的响应。 – TheSharpieOne 2014-09-25 20:07:00

+0

+1,但还不是我所希望的。 – 2014-09-25 20:10:00