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

守給你的承諾、 提交于 2019-12-03 16:12:39

问题


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


回答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.




回答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], [error])
non-GET "class" actions: Resource.action([parameters], postData, [success], [error])



来源:https://stackoverflow.com/questions/16579201/angularjs-how-to-handle-success-and-error-call-backs-with-ngresource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!