gpt4 book ai didi

javascript - 如何以 Angular 返回相互依赖的多个$http请求?

转载 作者:行者123 更新时间:2023-11-29 16:09:39 26 4
gpt4 key购买 nike

我有两个 url 端点:“fruitInfo”和“fruitDetails”

我想返回一个包含以下内容的对象:

var fruitInfoDetails = {"fruitInfo": <contents of fruitInfo response data>,
"fruitDetails": <contents of fruitDetails response data>}

在我调用的服务中:

var fruitInfoDetails = {};
this.getFruitInfo()
.then(function(data) {

fruitInfoDetails['fruitInfo'] = data;
this.getFruitDetails(data.nameOfFruit).then(function(data) {
fruitInfoDetails['fruitDetails'] = data;
})
});

假设 this.getFruitInfo() 和 this.getFruitDetauls() 包含返回 $http promise 到每个端点的函数。

执行此操作的正确/优雅方法是什么?如果有一个函数可以传递一个水果列表“[Apple, Pear, Orange]”,并且它可以返回一个 fruitInfoDetails 对象列表,那就完美了。

最佳答案

您可以使用 $q 服务做出您自己的 promise ,并在第二次调用完成时解决它。

angular.module('mymodule').factory('FruitService', function($http, $q) {
return {
getFruitInfoDetails: function() {
// make our own promise
var deferred = $q.defer();
// 1st call
$http.get("fruitInfo").then(function(fruitInfo) {
// 2nd call
$http.get("fruitDetails").then(function(fruitDetails) {

deferred.resolve({
fruitInfo: fruitInfo,
fruitDetails:fruitDetails
});
});
});
return deferred.promise;
}
};
});

您还可以使用 $q.all() 来等待两个请求完成后再解析。它会减少缩进。

angular.module('mymodule').factory('FruitService', function($http, $q) {
return {
getFruitInfoDetails: function() {
// make our own promise
var deferred = $q.defer();
// 1st call
var infoPromise = $http.get("fruitInfo");
var detailsPromise = $http.get("fruitDetails");

$q.all([infoPromise, detailsPromise]).then(function(data) {
deferred.resolve({
fruitInfo: data[0],
fruitDetails: data[1]
})
});

return deferred.promise;
}
};
});

请求检索给定水果的列表:

angular.module('mymodule').factory('FruitService', function($http, $q) {

return {
getFruitInfoDetails: function(fruit) {
// make our own promise
var deferred = $q.defer();

// we'll asume that you can put the fruit as part of the path
var infoPromise = $http.get("fruitInfo/" + fruit);
var detailsPromise = $http.get("fruitDetails/" + fruit );

$q.all([infoPromise, detailsPromise]).then(function(data) {
deferred.resolve({
fruitInfo: data[0],
fruitDetails: data[1]
})
});

return deferred.promise;
},

getFruitList: function(fruits) {
var deferred = $q.defer();

// map our list of fruits to a list of the promises of fruit info
var allPromises = fruits.map(function (fruit) {
return this.getFruitInfoDetails(fruit);
});

// wait for all the fruits to be resolved then just resolve our own promise
$q.all(allPromises).then(function(allTheFruitInfoDetails) {
deferred.resolve(allTheFruitInfoDetails);
});
return deferred.promise;
}
};
});

关于javascript - 如何以 Angular 返回相互依赖的多个$http请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32212135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com