我想用$ q将此金字塔请求更改为承诺。
app.controller('Ctrl', function ($scope, $http, $q) {
$http.post('http://localhost:1235',data_post1).success(function (data){
console.log("1");
$http.post('http://localhost:1236',data_post2).success(function (data){
console.log("2");
$http.post('http://localhost:1237',data_post3).success(function (data){
console.log("3");
$http.post('http://localhost:1238',data_post4).success(function (data){
console.log("4");
});
});
});
});
}
我之前从未使用过$ q。
答案 0 :(得分:1)
所以最佳做法是将http请求拉出控制器
所以,如果你有像
这样的工厂app.factory("fooSrvc", ["$q", "$http", function($q, $http){
return {
data1: function(postData){
var deferred = $q.defer();
$http.post("", postData).success(function(results){
deferred.resolve(results);
});
return deferred.promise;
},
data2: function(postData){
var deferred = $q.defer();
$http.post("", postData).success(function(results){
deferred.resolve(results);
});
return deferred.promise;
}
};
}]);
然后你的控制器看起来像
app.controller("Ctrl", ["$scope", "fooSrvc", function($scope, fooSrvc){
fooSrvc.data1(dataTopost).then(function(results){
// do something with it here possibly
fooSrvc.data2(moreDataToPost).then(function(moreResults){
// do something with it here possibly
});
});
}]);