2014-09-25 92 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