描述這種情況並不容易,但基本上我有一個作爲提供程序設置的服務,所以我可以對其進行配置。它有一個在我的項目中使用的API數組,最初是空的。各種配置塊可以添加一個API對象到數組,這似乎是工作。我console.log每次輸出和數組正在增長。當服務注入到其他地方時,角度提供程序配置重置
我再注入我的服務成別的東西(在這種情況下的$ HTTP攔截功能)和使用服務的方法返回數組,但每次我得到一個空數組。
我認爲這樣做的方式是所有的配置塊首先運行,並且被攔截的$ http調用正在發生,因此數組在截獲時應該充滿API。
總之,這裏的一些代碼
angular.module('authModule').provider('authService', function(){
var _apis = [];
return({
addApi: addApi,
$get: instantiateAuth
});
function addApi(newApi){
_apis.push(newApi);
console.log("API added", _apis);
}
function instantiateAuth() {
return({
getApis: function(){
console.log("Getting APIs", _apis);
return _apis;
}
});
}
})
.config(function($httpProvider){
$httpProvider.interceptors.push(function($log, $rootScope, $q) {
return {
request: function(config) {
var injector = angular.injector(['ng', 'authModule']);
var authService = injector.get('authService');
console.log("apis", authService.getApis());
}
};
});
});
和示例配置塊
angular.module('myModule').config(function ($provide, authServiceProvider) {
authServiceProvider.addApi({
url: 'https://apiurl.com',
other: 'stuff'
});
authServiceProvider.addApi({
url: 'https://apiurl2.com',
other: 'stuff'
});
});
所以,每個appApi方法被稱爲在一個配置塊(這裏兩次)時,這條線輸出array console.log(「API added」,_apis);並在第一次通話後正確輸出1個項目,在第二次通話後正確輸出兩個項目。
當這個碼 - authService.getApis() - 觸發首次HTTP調用被攔截,它記錄一個空數組到控制檯。
任何幫助真的不勝感激。
編輯:
這個問題似乎是該行
變種注射器= angular.injector([ 'NG', 'authModule']);
我的供應商似乎是復位/重新每發生這種情況時,也許我誤解了如何使用注射器。我最初只是注入我的authService在函數參數中的正常方式,但我得到了一個循環依賴(我的認證服務需要打開一個模式窗口,但angular-ui模式依賴於http服務,我的http調用被攔截到檢查與用戶進行身份驗證:(我的身份驗證服務)
謝謝。這是我試圖繞過循環依賴的第一件事,但$ injector.get('authService')返回undefined,儘管$ injector.has('authService')返回true。我發現這很奇怪,所以嘗試使用angular.injector,而不是(錯誤地)。我已經把它重新放回到你已經顯示的方式工作,它不再返回undefined。不知道爲什麼,但我很高興它的工作。 – jonhobbs