Reputation: 2084
In my factory I have this function which calls a delete api as following :
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';
});
},
this function works.
and then I want to delete multiple entries so I use this function for that :
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;
}
in the server side all entries are deleted, but in my browser console I get this error :
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
I call this function from my controller as following :
offresFactory.removeSelectedItems(entriesToDelete).then(function (state) {
if(state == true) $state.go($state.current, {}, {reload: true});
}, function (error) {
console.log(error);
});
How can I solve this ?
Upvotes: 0
Views: 1168
Reputation: 395
You are deleting multiple items and obtain multiple responses for those. You can use Angular's $q.all
to turn the list of result promises you create by the $http.delete
into a result list promise which you can then return.
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
})
}
Your attempt with the local variable deleted
won't work as you have to wait for the promises created by $http.delete
to be fulfilled.
Upvotes: 2