Trying to wrap my head around a rather complex issue here. I have a service set up as a provider in order to configure it. Initially, this service has an empty array of APIs which can be dynamically added to by various configuration blocks. When adding APIs, I can see the array growing with console.log messages.
However, when I inject this service into something else, like an $http interceptor function, and try to retrieve the array using a service method, I keep getting an empty array.
I believed that since all config blocks run first, by the time the $http call interception happens, the array should already be populated with APIs. But that doesn't seem to be the case.
Below is some sample code:
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());
}
};
});
});
And here's an example of a config block:
angular.module('myModule').config(function ($provide, authServiceProvider) {
authServiceProvider.addApi({
url: 'https://apiurl.com',
other: 'stuff'
});
authServiceProvider.addApi({
url: 'https://apiurl2.com',
other: 'stuff'
});
});
Despite seeing the array grow with each call to the addApi method in the config block, the array appears empty when accessed through authService.getApis() during the HTTP call interception.
Any insights or assistance on this puzzling issue would be greatly appreciated.
UPDATE:
The crux of the problem seems to lie in this line of code:
var injector = angular.injector(['ng', 'authModule']);
It appears that my provider is being reset or recreated each time this line executes. Perhaps my understanding of how the injector works is flawed. Initially, I tried injecting my authService directly as a parameter in the function, but faced a circular dependency due to the need for authentication service to open a modal window which relies on http service, while my http calls are intercepted by the authentication service for user authentication checks.