0

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 ?

1
  • You are returning response in method removeSelectedItems but you never define a variable named response. Commented Mar 23, 2016 at 14:36

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.