What does AngularJS $resource.delete() return?

230 Views Asked by At

I am using AngularJS $resource to list, create, and update resources and it works fine. For example:

getFoo = (fooId) => {
  const Foo = $resource("api/foos/:fooId);
  return Foo.get({fooId});
};

This returns a Foo instance that has a Foo.$promise I can use to see when the request finishes.

But what if I want to delete a Foo?

deleteFoo = (fooId) => {
  const Foo = $resource("api/foos/:fooId);
  return Foo.delete({fooId});
};

All the examples I can find show Foo.delete({fooId}), but never tell what it returns. How can I get a promise to know when deletion is successfull?

Does Foo.delete({fooId}) return a Foo $resource with a Foo.$promise, just like get()? But that would be odd to have a resource of a thing I've just deleted. Does it return the $promise itself? Does it return the underlying $http object?

In short, how can I get a promise from Foo.delete({fooId}) to know when deletion has been successful?

1

There are 1 best solutions below

1
James-Jesse Drinkard On

From the documentation:

The action methods on the class object or instance object can be invoked with the following parameters:

"class" actions without a body: Resource.action([parameters], [success], [error])
"class" actions with a body: Resource.action([parameters], postData, [success], [error])
instance actions: instance.$action([parameters], [success], [error])

A delete would be an action without a body, so if you are wanting to verify your delete was succesfull, then you need to send success and error with the action.

Here is an example using an entity id:

 var entityResource = $resource('/api/:entityType/:entityId', 
                                   {type:'@entityType', id: '@entityId'});
    
    entityResource.delete({type: $scope.entityType, id: entityId}, success, failed);

Your success or failed would look something like this:

var success = function (result) {
    $scope.remove($scope.table.data, idColumn, entityId);
};

var failed = function (result) {
    alert("You action has failed with: " + result);