How to execute a callback at the end of a $ http promise, to work on success or not?

3

In the Angle, I am executing a call HTTP through $http.get , and when this request ends, I change the value of a variable through callback in then :

$scope.carregando = true;

$http.get('/users/list').then(function (response) {
     $scope.carregando = false;
});

However, if this request fails, the value of $scope.carregando is not changed.

I know it's possible to pass a second parameter to handle crashes, like this:

$http.get('/users/list').then(function (response) {
     $scope.carregando = false;
}, function () {
     $scope.carregando = false;
});

But I do not think it's a good idea to repeat code like this every time I need to do something both on success and failure.

Is there any method in the Angular promise that executes a callback when the request is terminated, regardless of whether there are faults (error 500 and similar) or not?

    
asked by anonymous 07.11.2017 / 19:03

1 answer

8

There is yes, finally is executed regardless of success / failure of the request in this way it is not necessary to repeat code:

$http.get('/users/list').then(function (response) {
   // código para tratamento do sucesso da requisição
 }, function () {
   // código para tratamento do erro da requisição
 }).finally(function() {
   $scope.carregando = false;
 });
    
07.11.2017 / 19:13