我已经尝试了所有可以找到的方法,建议将promise对象返回到resolve,以便我的函数将异步处理,但仍然无法返回正确的数据 - 请告知:
.state("app.deals.private", {
url: "/private/",
resolve: {
dealsFeatured: function(Deals, $rootScope) {
return Deals.getDeals('FEATURED', function(data) {
// console.log('deals featured', data); // DATA IS HERE
$rootScope.loading = false;
return data;
});
},
dealsGeneral: function(Deals, $rootScope, dealsFeatured) {
return Deals.getDeals('GENERAL', function(data) {
// console.log('deals general', data); // DATA IS HERE
$rootScope.loading = false;
return data;
});
},
dealsCats: function(Deals, dealsFeatured, dealsGeneral, $q) {
// ALL DEPENDENCIES HAVE DATA HERE
// build a promise object
var deferred = $q.defer();
Deals.mergeCats(dealsFeatured, dealsGeneral, $q, function(data){
console.log("received dealsCats: " + data);
//BUT....NOTHING IS RETURNED HERE, WHY NOT?!?!?!?
deferred.resolve(data);
});
//return the promise object
return deferred.promise;
},
这是我服务中的代码(注意数据是正确的,并在回调之前输出到控制台:
api.service('Deals', function(){
this.mergeCats = function(dealsFeatured, dealsGeneral, $q, callback){
// make one big array
var allCats = [];
if(Array.isArray(dealsFeatured.data.discountTermsWithCounters.cats)){
allCats = dealsFeatured.data.discountTermsWithCounters.cats;
}
if(Array.isArray(dealsGeneral.data.discountTermsWithCounters.cats)){
allCats = allCats.concat(dealsGeneral.data.discountTermsWithCounters.cats);
}
// now recreate the array into something we can work with
var newCats = [];
angular.forEach(allCats, function(value, key){
if(newCats[value.title]){
newCats[value.title].count += value.count;
} else {
newCats[value.title] = value;
}
});
// after all is completed, return data to the promise object
$q.all(allCats).then(function () {
console.log('newCats',newCats); // CORRECT DATA IS OUTPUTTED HERE
// newCats data looks like this in console:
// Array: [Herbs & Homeopathic: Object, Frozen: Object, Groceries: Object, Body Care: Object, General Merchandise: Object…]
callback(newCats);
});
};
});
请告知,我错过了什么?
答案 0 :(得分:0)
您对dealsCats
和Deals.mergeCats
感到困惑,以及如何以及为何使用$q
作为参数传递。
mergeCats
会$q.all
返回一个承诺,但mergeCats
只执行同步操作。不需要$q
,承诺或回调:
因此,请将Deals.mergeCats
更改为以下内容:
this.mergeCats = function(dealsFeatured, dealsGeneral){
// some other code here that creates allCats
return allCats;
}
出于同样的原因,您$q.defer
不需要dealsCats
:
resolve: {
//...,
dealsCats: function(Deals, dealsFeatured, dealsGeneral){
return Deals.mergeCats(dealsFeatured, dealsGeneral);
}
}