我是棱角分明的新手并且遇到了问题。我创建了一个调用服务的控制器,数据填充在屏幕上。但是,我试图在使用.then调用第一个函数后执行函数,并且我没有收到任何数据,就好像它不存在一样。为什么我的控制台声明为空?
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
});
答案 0 :(得分:1)
请尝试以下操作,无论何时进行ajax调用,都应始终使用promises。这样,您确保解决所有请求。
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);
})
});