Reputation: 435
I am new to angular and am stuck on an issue. I have created a controller which calls a service and the data is populating the screen. However, I am trying to execute functions after the first function has been called using .then and I am not receiving any data as if it doesn't exist. Why is my console statement empty?
app.service('UserOperations',function($http, $q){
$http.defaults.useXDomain = true;
this.getStores = function(user_id){
var userStores;
var stores = [];
$http.get("http://localhost/shoploot_api/api/get-user-stores?user_id=" + user_id + "&&action=get_user_stores")
.then(function (res) {
userStores = res.data;
angular.forEach(userStores, function(value, key){
$http.get("http://localhost/shoploot_api/api/get-store?store_id=" + value.store_id + "&&action=get_store")
.then(function (store) {
$http.get("http://localhost/shoploot_api/api/get-points?store_id=" + value.store_id + "&&user_id=" + user_id)
.then(function (points) {
if(points.data[0]['points']){
store.data[0]['points'] = points.data[0]['points'];
}else{
store.data[0]['points'] = 0;
}
store.data[0]['newMessage'] = 'hello';
stores.push(angular.merge(userStores[key],store.data[0]));
});
});
});
});
return stores;
};
this.getMessages = function(user_id,store_id){
return 'working';
}
});
app.controller('userStoresCtrl', function($scope, $q, UserOperations){
var getStores = function(user_id){
var defer = $q.defer();
$scope.stores = UserOperations.getStores(user_id);
defer.resolve($scope.stores);
return defer.promise;
}
getStores(1).then(function(){
console.log($scope.stores);
});
//$scope.stores = stores
});
Upvotes: 1
Views: 98
Reputation: 2777
Try this below, you should always use promises whenever you make ajax calls. That way, you make sure to resolve all requests.
app.service('UserOperations', function ($http, $q) {
$http.defaults.useXDomain = true;
this.getStores = function (user_id) {
var userStores;
var stores = [];
var deferred = $q.defer();
$http.get("http://localhost/shoploot_api/api/get-user-stores?user_id=" + user_id + "&&action=get_user_stores")
.then(function (res) {
userStores = res.data;
angular.forEach(userStores, function (value, key) {
$http.get("http://localhost/shoploot_api/api/get-store?store_id=" + value.store_id + "&&action=get_store")
.then(function (store) {
$http.get("http://localhost/shoploot_api/api/get-points?store_id=" + value.store_id + "&&user_id=" + user_id)
.then(function (points) {
if (points.data[0]['points']) {
store.data[0]['points'] = points.data[0]['points'];
} else {
store.data[0]['points'] = 0;
}
store.data[0]['newMessage'] = 'hello';
stores.push(angular.merge(userStores[key], store.data[0]));
deferred.resolve(stores);
});
});
});
});
return deferred.promise;
};
this.getMessages = function (user_id, store_id) {
return 'working';
}
});
app.controller('userStoresCtrl', function ($scope, $q, UserOperations) {
UserOperations.getStores(user_id)
.then(function(response) {
console.log(response);
})
});
Upvotes: 1