Search code examples
javascriptangularjsangularjs-service

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


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


Solution

  • 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.