Evaluating the $http response from Factory to the controller in Angularjs

Asked

Viewed 62 times

1

I created a Factory to carry out the operations CRUD in a REST API using the $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 answer in cases of erro in my controller ?

1 answer

1


You can directly pass the promise and use the .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);
  });
};
  • I’ve been researching there ...a concept called Interceptors I’ll see if I can implement it to make the error handling for the HTTP request methods... I’m still studying about it so I haven’t chosen as response .... but this concept and very interesting I think would even create another question ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.