AngularJS: How to handle success and error call backs with ngResource?

All we need is an easy explanation of the problem, so here it is.

The docs does not give any idea about it.

My REST enpoint might throw error

$scope.delete = function(index) {
    Transaction.delete({transactionId: $scope.transactions[index].uuid})     

I changed the above to following

$scope.delete = function(index) {
    Transaction.delete({transactionId: $scope.transactions[index].uuid})
      .success('transaction deleted');

But it fails

TypeError: Object #<Resource> has no method 'success'
    at Object.TransactionController.$scope.delete (http://localhost:5000/static/app/js/controllers/transactionController.js:26:8)
    at http://localhost:5000/static/app/lib/angular/angular.js:6094:36

How can I handle success and error scenarios?

P.S. I am new to JavaScript

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can pass in a success a error callback using the following formats depending on how you are using the Resource (taken from the docs):

  • HTTP GET “class” actions: Resource.action([parameters], [success], [error])
  • non-GET “class” actions: Resource.action([parameters], postData, [success], [error])
  • non-GET instance actions: instance.$action([parameters], [success], [error])

Your example is similar to the non-get “class” actions and would look something like this:

Transaction.delete({transactionId: $scope.transactions[index].uuid}, 
    function(successResult) {
        // do something on success
    }, function(errorResult) {
        // do something on error
        if(errorResult.status === 404) {            

Here is a related question regarding a failed GET resource.

Method 2

Pass in the success and fail callback functions as arguments.

Transaction.delete({transactionId: $scope.transactions[index].uuid}, 
                   function(data) {
                      // success
                   }, function(e) {
                      // failure

From the docs you linked:

HTTP GET “class” actions: Resource.action([parameters], [success],
non-GET “class” actions: Resource.action([parameters],
postData, [success], [error])

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply