gpt4 book ai didi

api - AngularJS 中单个 $http 请求的多个 promise

转载 作者:行者123 更新时间:2023-12-04 08:11:45 25 4
gpt4 key购买 nike

我想在我的 AngularJS 应用程序中实现 promise ,就像你在这个例子中看到的那样:https://stackoverflow.com/a/12360882/371273

我的应用程序将获取多个数据数组,在我的服务器上进行多次数据库访问,但我已将服务器配置为返回所有这些数据作为一个响应,以尽量减少请求以保持我的应用程序尽可能高效(除非所有数据到达客户端,否则数据基本上是无用的)。所以不要这样做......

MyCtrl.resolve = {
projects : function($q, $http) {
return $http.get('/api/projects'});
},
clients : function($q, $http) {
return $http.get('/api/clients'});
}
};

我希望能够向 /api/allData 之类的 URL 发出 single $http GET 请求,然后拥有projects 的 promise 将设置为等于 allData.projectsclients 的 promise 将设置为等于 allData。客户端 等(其中allData 是我的single 请求返回的数据)。我对 Promise 还是很陌生,谁能给我一个示例,说明如何在 MyCtrl.resolve 中设置这些 Promise?

最佳答案

我相信这就是您正在寻找的:

var myApp = angular.module('myApp', []);

myApp.factory('myService', function ($http, $q) {
return {
getAllData: function () {
return $q.all([
// $q will keep the list of promises in a array
$http.get('/api/projects'),
$http.get('/api/clients')
]).then(function (results) {
// once all the promises are completed .then() will be executed
// and results will have the object that contains the data
var aggregatedData = [];
angular.forEach(results, function (result) {
aggregatedData = aggregatedData.concat(result.data);
});
return aggregatedData;
});
}
};
});

您可以从最终 aggregatedData 中获取数据数组(例如:aggregatedData[0]、aggregatedData[1]、...)

您可以通过一次调用在 MyCtrl.resolve 中设置这些 promise :

resolve = {
getAllData : myService.getAllData()
}

关于api - AngularJS 中单个 $http 请求的多个 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14271713/

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