在我的工厂,我有这个函数调用delete api如下:
removeOffre: function(id) {
return $http.delete('http://localhost:8080/removeOffre/'+id)
.then(function(response) {
return response;
}, function(error) {
return 'There was an error getting data';
});
},
此功能有效。
然后我想删除多个条目,所以我使用此功能:
removeSelectedItems: function(selectedItems) {
let deleted = true;
angular.forEach(selectedItems,function(id){
$http.delete('http://localhost:8080/removeOffre/'+id)
.then(function(response) {}, function() {
deleted = false;
});
});
return response;
}
在服务器端删除所有条目,但在我的浏览器控制台中出现此错误:
Error: response is not defined
factory.removeSelectedItems@http://localhost:9000/scripts/providers/offresFactory.js:60:7
deleteSelectedItems/$scope.ok@http://localhost:9000/scripts/controllers/offreController.js:135:5
anonymous/fn@http://localhost:9000/scripts/js/angular.min.js line 212 > Function:2:194
我从我的控制器调用此函数如下:
offresFactory.removeSelectedItems(entriesToDelete).then(function (state) {
if(state == true) $state.go($state.current, {}, {reload: true});
}, function (error) {
console.log(error);
});
我该如何解决这个问题?
答案 0 :(得分:2)
您正在删除多个项目并获取多个回复。您可以使用Angular的$q.all
将您创建的结果承诺列表转换为结果列表承诺,然后返回。
$http.delete
您尝试使用本地变量removeSelectedItems: function(selectedItems) {
return $q.all(selectedItems.map(function(id) {
return $http.delete('http://localhost:8080/removeOffre/' + id);
})).then(
function(responses) {
return true; // all were successful
},
function(error) {
return false; // there was at least one error
})
}
将无效,因为您必须等待deleted
创建的承诺得以履行。