我有一个控制器调用一个服务,它执行一些http调用并将一组数据返回给我的控制器。我面临的问题是我的服务在所有http调用完成之前返回一些数据(通常是emtpy),因此$ scope.myForksLinks未定义。
控制器:
myService.getMyData()
.then(function(response) {
$scope.myUrl = response.myForksLinks;
});
为MyService:
handleResolveReject() {
return promise.then(function(v) {
return {v:v, status: "resolved"};
}, function(e) {
return {e:e, status: "rejected"};
});
},
getMyData() {
const that = this;
var deferred = that._$q.defer();
var httpResponse = [];
var httpLinks = [
{myTablesLinks: this.tablesLinks}, // this.tablesLinks = [http://tablelink1.come, http://anotherTableLink.com]
{myGlassesLinks: this.glassesLinks},
{myPlatesLinks: this.platesLinks},
{myCupsLinks: this.cupsLinks},
{myForksLinks: this.forksLinks},
]
var getData = function() {
_.forEach(httpLinks, function(httpSet, k) {
_.forEach(httpSet, function(links, httpName) {
var promises = [];
angular.forEach(links, function(link) {
var promise = that._$http({
method: 'GET',
url: link + '/my/end/point',
responseType: 'json'
});
promises.push(promise)
});
return Promise.all(promises.map(that.handleResolveReject))
.then(function(results)) {
httpResponse.push({httpName: results.filter(x => x.status === 'resolved')});
});
});
});
return httpResponse;
};
deferred.resolve(getData());
return deferred.promise;
}
答案 0 :(得分:0)
这些方面的东西:
var allPromises = [];
_.forEach(httpLinks, function (httpSet, k) {
allPromises = _.map(httpSet, function (links, httpName) {
var promises = [];
angular.forEach(links, function (link) {
var promise = that._$http({
method: 'GET',
url: link + '/my/end/point',
responseType: 'json'
});
promises.push(promise);
});
return Promise.all(promises.map(that.handleResolveReject))
.then(function (results) {
httpResponse.push({ httpName: results.filter(x => x.status === 'resolved') });
});
});
});
Promise.all(allPromises).then(() => {
// here you go
})