Angularjs 解决从简单函数返回数据到UI路由器的问题
我已经尝试了所有我能找到的建议将承诺对象返回到解析的方法,以便我的函数将异步处理,但仍然无法获得返回的正确数据-请建议:Angularjs 解决从简单函数返回数据到UI路由器的问题,angularjs,angular-ui-router,angular-promise,Angularjs,Angular Ui Router,Angular Promise,我已经尝试了所有我能找到的建议将承诺对象返回到解析的方法,以便我的函数将异步处理,但仍然无法获得返回的正确数据-请建议: .state("app.deals.private", { url: "/private/", resolve: { dealsFeatured: function(Deals, $rootScope) { return Deals.getD
.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);
});
};
});
请告知,我遗漏了什么?您对
dealsCats
和Deals.mergeCats
以及如何以及为什么将$q
作为参数使用和传递感到困惑
mergeCats
执行$q。返回承诺的所有
,但mergeCats
仅执行同步操作。无需执行$q
、承诺或回调:
因此,将Deals.mergeCats
更改为以下内容:
this.mergeCats = function(dealsFeatured, dealsGeneral){
// some other code here that creates allCats
return allCats;
}
出于同样的原因,对于dealsCats
,您不需要$q.defer
:
resolve: {
//...,
dealsCats: function(Deals, dealsFeatured, dealsGeneral){
return Deals.mergeCats(dealsFeatured, dealsGeneral);
}
}
我最初尝试过,但没有成功,这就是为什么我认为它需要返回一个承诺对象。我会再试一次,正如你所说,让你知道它是否有效。好的,我已经确认数据确实正在传递到控制器,我遇到的问题是数组的格式-角度ui路由器不会传递a将对象作为模板的值的关联数组,因此我将其转换为对象,现在它可以完美地工作。感谢您帮助我解决实际问题!