2015-10-15 45 views
0

我正在使用Restangular在單個頁面中處理我的令牌/標頭認證Angular Web應用程序。 使用addFullRequestInterceptor,我爲每個傳出REST API調用設置正確的標頭,使用個人密鑰來加密數據。刪除或覆蓋Restangular中作用域配置的請求攔截器

Restangular 
     .setBaseUrl(CONSTANTS.API_URL) 
     .setRequestSuffix('.json') 
     .setDefaultHeaders({'X-MyApp-ApiKey': CONSTANTS.API_KEY}) 
     .addFullRequestInterceptor(requestInterceptor) 
     .addErrorInterceptor(errorInterceptor); 

function requestInterceptor(element, operation, route, url, headers, params, httpConfig) { 
     var timeStamp = Helpers.generateTimestamp(), 
      //Condensed code for illustration purposes 
      authSign = Helpers.generateAuthenticationHash(hashIngredients, key, token), 
      allHeaders = angular.extend(headers, { 
       'X-MyApp-Timestamp': timeStamp, 
       'Authentication': authSign 
      }); 

     return { 
      headers: allHeaders 
     } 
    } 

很好用。我需要一個例外:對於尚未登錄的新訪問者,通過REST請求一個通用密鑰/令牌對。此密鑰/令牌對用於登錄身份驗證調用的標頭中。 因此,對於此調用,我創建了一個單獨的Restangular子配置。在這個配置中,我想覆蓋requestInterceptor。但是這似乎被忽略了(即原始攔截器仍被稱爲)。無論我傳遞null還是返回空對象的函數都沒關係。

var specialRestInst = Restangular.withConfig(function(RestangularConfigurer) { 
       RestangularConfigurer.addFullRequestInterceptor(function() {return {}}); 
      }), 
      timeStamp = Helpers.generateTimestamp(), 
      header = {'X-MyApp-Timestamp': timeStamp}; 

     specialRestInst.one('initialise').get({id: 'app'}, header) 

因此,如Restangular所記錄的,withConfig會採用基本配置並對其進行擴展。我想知道如何removeFullRequestInterceptor(這個函數不存在),覆蓋它,或類似的東西。

回答

0

我會採取不同的方法,並嘗試將標誌傳遞給攔截器。如果該標誌存在,則排除authSign。你可以使用withHttpConfig來做到這一點。最好排除特殊情況,然後始終告訴攔截器包含authSign

所以你要更新這樣的攔截器。

function requestInterceptor(element, operation, route, url, headers, params, httpConfig) { 
    var timeStamp = Helpers.generateTimestamp(); 
    var allHeaders = {'X-MyApp-Timestamp': timeStamp}; 
    if(!httpConfig.excludeAuth) { 
     //Condensed code for illustration purposes 
     var authSign = Helpers.generateAuthenticationHash(hashIngredients, key, token); 
     allHeaders['Authentication'] = authSign; 
    } 
    return angular.extend(headers, allHeaders); 
} 

當您需要排除authSign時,您可以使用像這樣的restangular。

specialRestInst.withHttpConfig({excludeAuth: true}).get({id: 'app'}); 

你應該能夠對任何值添加到HTTP配置你想要的,因爲他們是不是已經使用很長。

我不確定這是否會按預期工作,但我不明白爲什麼它不起作用。

+0

這是我猜測的一個選項。我已經設法通過檢測'route'參數是什麼來解決這個問題。但是如果可以做出子配置,我預計攔截器可以被覆蓋。所以我希望有人知道如何(或知道爲什麼不可能)。 – Micros