Evaluating the $ http response from the factory to the controller in AngularJS

1

I've created a Factory to perform the operations CRUD in a api REST using $ http service to make a user control.

Factory

//Listar..Recuperar ..Inserir ...Editar..{...}
usuarioService.Excluir = function (id) {
        var promise = $http({
            method: 'DELETE',
            url: API_URL.url + '/api/v1/usuario/' + id
        })
            .then(function (response) {
                return response.data;
            },
            function (response) {
                return alert(response.statusText + ' ' + response.data.errors + ' ' + response.data.message);
            });
        return promise;
    };

Controller

//Listar..Recuperar ..Inserir ...Editar..{...}
vm.Excluir = function Excluir() {
            usuarioService.Excluir(vm.id).then(function (result) {
                $location.path("/usuario");
            })
        };

How can I capture the response in erro cases in my controller ?

    
asked by anonymous 23.08.2017 / 15:16

1 answer

1

You can directly pass the pledge and use .catch to handle the error.

Factory:

//Listar..Recuperar ..Inserir ...Editar..{...}
usuarioService.Excluir = function (id) {
  return $http({
      method: 'DELETE',
      url: API_URL.url + '/api/v1/usuario/' + id
  });
};

Controller

vm.Excluir = function Excluir() {
  usuarioService.Excluir(vm.id).then(function(result) {
    console.log(result.data);
    $location.path("/usuario");
  }).catch(function(response) {
    alert(response.statusText + ' ' + response.data.errors + ' ' + response.data.message);
  });
};
    
23.08.2017 / 15:23