How to get an answer using ngResource

1

I have a controller with which I could ( finally ), save a record in my database, which is this:

  function PuestoAddController(puestosService, puesto){
    var self = this;
    var _puesto = puesto;

    function _add(_puesto){
      console.log("Puesto: " + _puesto.clave + " - " + _puesto.nombre + " - " + _puesto.orden);
      puestosService.save(_puesto, function(){
        console.log('Registro Guardado');
      });
    }

    self.add = _add;
  }

This works as expected, but I need to get the response from the server, for example, if it was successful, I get the code 201 , but it could be an error message of type Esta clave ya está registrada .

From the response received, I will schedule the actions that are necessary, for example, clean the form, send to another page, etc.

My service is this:

(function(angular){
  'use strict';

  angular.module('cmi')
    .factory('puestosService', PuestosService);

  PuestosService.$inject = ['$resource', 'config', 'session'];

  function PuestosService($resource, config, session){
    var puestosURL = config.baseURL + config.apiURL + '/capine/puesto/:id/';
    return $resource(
      puestosURL,
      {id: '@id'},
      {
        'get': {cache: true, isArray: false},
        'query': {method:'GET', isArray: true, cache: true},
        'save': {
          method: 'POST',
          headers: {'Authorization': 'Token '+ session.getAccessToken()}
        }
      }
    );
  }
})(angular);
  

In the module documentation there is an action called transformResponse , but unfortunately not offer no example of use.

Question

How can I get the response from the RESTful server if I use ngResource ( $resource ) in AngularJS 1.x?

Thanks for your time.

    
asked by toledano 24.11.2016 в 21:02
source

1 answer

3

Another way to do this is to use the $promise property, for example:

puestosService.save(_puesto).$promise
  .then(function(response){
    console.log(response);
  })
  .catch(function(error){
    console.error(error);
  });
    
answered by 24.11.2016 / 21:18
source