I have a scenario where one factory sends a POST request to receive key-value pairs in JSON format:
.factory('DataFetcher', ['$resource',
function($resource) {
// Returns JSON key-value pairs, for example "{'foo', 'bar'}"
return $resource('api/fetch-data', {}, {
get: {
method: 'POST'
}
});
}])
Another factory is designed to be used by controllers to access a specific value based on its key:
.factory('ValueAccessor', ['DataFetcher',
function(DataFetcher) {
var data;
DataFetcher.get(function(response) {
data = response;
});
return {
get: function(key) {
return data[key];
}
};
}])
The issue arises when calling ValueAccessor.get('foo')
, the data
object from the ValueAccessor
factory is not initialized yet (as DataFetcher.get
is asynchronous), resulting in a
TypeError: Cannot read property 'foo' of undefined
:
.controller('SomeController', ['ValueAccessor',
function (ValueAccessor) {
console.log(ValueAccessor.get('foo')); // error
}])
Any suggestions on how to resolve this situation?