win*_*toy 3 api asynchronous angularjs
我想在我的AngularJS应用程序中实现promises,就像你在这个例子中看到的那样: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'});
}
};
Run Code Online (Sandbox Code Playgroud)
我希望能够向一个URL 发出一个单一的 $http GET请求/api/allData,然后projects将其设置为等于,并将对此allData.projects的承诺clients设置为allData.clients等等.(allData返回的数据在哪里)我的单一要求).我对承诺还很新,有人能给我一个例子,告诉我如何在里面设立这些承诺MyCtrl.resolve吗?
我相信这就是你要找的东西:
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;
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
您可以从最终aggregatedData数组中获取数据(例如:aggregatedData [0],aggregatedData [1],...)
您可以在一次调用中在MyCtrl.resolve中设置这些promise:
resolve = {
getAllData : myService.getAllData()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6003 次 |
| 最近记录: |