2016-07-23 108 views
0

我有一個Angular應用程序,它可以爲多個位置重複使用相同的模板。網址看起來像:使用ui-router stateParams和攔截器更新所有api請求

/locations/location1/ 
/locations/location2/ 
/locations/location1/about 
/locations/location2/about 

而且我的狀態設置,設置了這我的其他路線設置爲其父的位置PARAM:

$stateProvider 
    .state('root', { 
    url: '/locations/{location:[^/]*}', 
    abstract: true, 
    template: '<ui-view/>' 
    }); 

在這些頁面模板,我有幾個組件提出API請求。我想要做的是攔截所有的HTTP請求的API和基於在$ stateParams位置屬性預先設置的位置ID:

function apiInterceptor ($stateParams) { 
    return { 
    request: (config) => { 
     config.url = $stateParams.location + '/' + config.url; 
     return config; 
    } 
    }; 
} 

module 
.factory('apiInterceptor', apiInterceptor) 
.config(function($httpProvider { 
    $httpProvider.interceptors.push('apiInterceptor'); 
} 

不幸的是這給了我一個循環依賴:

ng1UIRouter <- $stateParams <- apiInterceptor <- $http <- ng1UIRouter 

我相信我可以直接使用$注入器來解決循環依賴問題,但是我已經讀到,遇到這個問題意味着你可能有某種架構問題。有沒有更好的方式來獲取位置ID,而不需要重複遍歷各個API請求的代碼?

回答

0

對於循環依賴,你可以手動注入使用$injector

嘗試

function apiInterceptor ($injector) { 
    var $stateParams = $injector.get('$stateParams'); 
    return { 
    request: (config) => { 
     config.url = $stateParams.location + '/' + config.url; 
     return config; 
    } 
    }; 
} 
+0

感謝的服務。其實我在帖子底部提到了注射器解決方案。但是,我想知道是否有更好的方法來構建解決方案。循環依賴顯然表明你的思想出了問題。 – jhummel