我目前有一个工厂提交带有数据的 POST 请求。
这是工厂:
app.factory('Quotes', ['$http',function($http, $q) {
var urlBase = 'http://test-url.com';
var Quotes = {};
Quotes.createQuote = function (data) {
return $http.post(urlBase + '/', data)
};
return Quotes;
}]);
我有一个对象数组,每个对象都需要在其自己的 POST 请求中单独提交。 我有这个控制器..
我正在将$scope.array传递给saveQuote()函数。
$scope.saveQuote = function(data){
$rootScope.loading = true;
angular.forEach(data, function(quote){
Quotes.createQuote(quote)
.success(function (data, status, headers, config) {
$rootScope.loading = false;
$rootScope.status = {header: "Success", message: "Success", type: "success"};
})
.error(function (data, status, headers, config) {
$rootScope.status = {header: "Error", message: data};
});
});
}
当所有帖子请求都完成后,如何创建函数?
更新:
另外,如何为每个开机自检输出每个错误响应? 似乎下面的答案只输出其中之一?
使用 $q 服务
$scope.saveQuote = function(data){
$rootScope.loading = true;
var createdQuotes = [];
angular.forEach(data, function(quote){
createdQuotes.push(Quotes.createQuote(quote));
});
$q.all(createdQuotes).then(function() {
//do something now that all the quotes are created
$rootScope.loading = false;
$rootScope.status = {header: "Success", message: "Success", type: "success"};
}, function(data) {
$rootScope.status = {header: "Error", message: data};
});
}
Quote.createQuote
将不得不回报承诺才能完成这项工作。
更好的是,您可以将forEach
更改为map
,将第一部分减少到一行,如下所示:
var createdQuotes = data.map(Quotes.createQuote);