How to run a callback at the end of a $http file, whether it works or not?

Asked

Viewed 510 times

3

At Angular, I’m running a call HTTP through the $http.get and, when this request ends, I change the value of a variable through the callback in the then:

$scope.carregando = true;

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

However, if there is a flaw in this request, the value of $scope.carregando is not changed.

I know that it is possible to pass a second parameter to deal with failures, thus:

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

But I don’t think it’s a good idea to repeat code like this every time I need to execute something both in case of success and in case of failures.

Is there any method in the Angular file that executes a callback when the request is terminated, regardless of failures (error 500 and the like) or not?

1 answer

8


There is, the finally is executed regardless of the success/failure of the request this way 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;
 });

Browser other questions tagged

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