handle error callback on save() method $ngResource

Aramillo picture Aramillo · Dec 10, 2014 · Viewed 9k times · Source

I need to handle error callback of an update operation, for this i'm using method save() like this:

$scope.save = function (params) {  
  MigParams.save(params);
};

Migparams service look like this:

angular.module('monitor').
    factory('MigParams', function ($resource) {        
        return $resource('/restful/migparams');    
});

This code works great but i need to know if an error occurs in database. I have searched in google but i didn't find this particular case. Is there a way of get this?. Thanks in advance

Answer

Ghan picture Ghan · Dec 10, 2014

From https://docs.angularjs.org/api/ngResource/service/$resource:

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

non-GET "class" instance: Resource.action([parameters], [success], [error])

$resource's save method falls into the non-GET 'class' instance category), so its error callback is the third argument.

Your code would look like:

$scope.save = function (params) {  
  MigParams.save(params, 
    function(resp, headers){
      //success callback
      console.log(resp);
    },
    function(err){
      // error callback
      console.log(err);
    });
};