我有一个工厂,它返回以下对象
返回{
getCuisines: function(cuisineNames){
if (typeof cuisineNames !== 'string' && typeof cuisineNames !== undefined) {
throw new Error('Cusine type should be a string or should not have value');
}
cuisineNames = cuisineNames || options.term;
cuisineNames = cuisineNames.split(',');
var promises=[];
cuisineNames.forEach(function(cuisine){
var defered = $q.defer();
options.term = cuisine + ' '+ 'food';
$http.get(url,{params: options}).success(function(data){
defered.resolve(data);
localStorageService.setDishes(cuisine,data.businesses);
console.log("Cuisine ="+cuisine);
console.log(data);
});
promises.push(defered.promise);
});
return $q.all(promises);
}
};
我使用
从控制器调用此工厂MyFactory.getCuisines('American,Indian,Italian,Mexican,Japanese,Korean').then(function(data){
console.log(data);
});
执行应用程序时。我把所有美食都当成韩国人。最后一个参数传递过来。
更新1:
我将代码更新为以下代码。删除$ q。推送$ http到promises数组仍然无法正常工作。同样的回应。我检查了我的服务器,所有拨打服务器的电话都是韩国食品。
return {
getCuisines: function(cuisineNames){
if (typeof cuisineNames !== 'string' && typeof cuisineNames !== undefined) {
throw new Error('Cusine type should be a string or should not have value');
}
cuisineNames = cuisineNames || options.term;
cuisineNames = cuisineNames.split(',');
var promises=[];
cuisineNames.forEach(function(cuisine){
options.term = cuisine + ' '+ 'food';
console.log(options.term); //I see different cuisine name here
promises.push($http.get(url,{params: options}).success(function(data){
localStorageService.setDishes(cuisine,data.businesses);
console.log(data);
}));
});
return $q.all(promises);
}
};
答案 0 :(得分:1)
您只获得韩语,因为它是迭代中的最后一个,并且会覆盖其他承诺。您希望push
承诺$http.get
请求,而不是您为捕获$http
结果而定义的延期者。
答案 1 :(得分:0)
一些事情:
答案 2 :(得分:0)
哼哼,没有看到网络活动很困难,但你没有从get $ http调用返回,请尝试使用该语法:
getCuisines: function(cuisineNames){
if (typeof cuisineNames !== 'string' && typeof cuisineNames !== undefined) {
throw new Error('Cusine type should be a string or should not have value');
}
cuisineNames = cuisineNames || options.term;
cuisineNames = cuisineNames.split(',');
var promises = cuisineNames.map(function(cuisine) {
options.term = cuisine + ' '+ 'food';
console.log(options.term);
return $http.get(url,{params: options})
.then(function(data){
localStorageService.setDishes(cuisine,data.businesses);
console.log(data);
return data;
});
});
return $q.all(promises);
}