I have to AngularJS services to load data to my app which are set up in essentially the same way, although one works and one does not.
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'])
.service('uniqueLists', function ($http) {
console.log("Getting Unique Lists")
var itemsToList = [
'designer',
'store',
'category'
]
var uniqueLists = {};
var promise = (function(){
console.log("Inside Function")
for (var i = 0; i<itemsToList.length; i++){
var item = itemsToList[i];
uniqueLists[item] = [];
$http.get('/api/uniques/' + item, { cache: true}).
success(function (data){
uniqueLists[item] = data.query;
console.log(i + " out of " + itemsToList.length);
if (i == itemsToList.length -1){
return uniqueLists;
}
});
};
})();
return promise;
})
I think my main issue is that the $http call is non-blocking. For instance, when I try to console.log(i + " out of " + itemsToList.length) I see:
3 out of 3
3 out of 3
3 out of 3
In turn, in my app when I try to use uniqueLists like so:
function homeCtrl($scope, $location, uniqueLists, userInfo){
uniqueLists.then(function(obj){
// Do stuff
});
}
I get the error TypeError: Object [object Object] has no method 'then'
Any ideas on how to fix this? The $http.get api call works just fine so I think it's just a blocking/async problem.