timeout to $http request (search for 5 seconds, if not found, returns 'error')

Asked

Viewed 230 times

0

I am setting up a $http request for zip code, it happens that sometimes the API takes too long to return a reply, and the user gets stuck to proceed at checkout.

function worked, but when I tried to add the timeout it stopped.

FUNCTION:

  if(this.cep && this.cep.length > 7) {
    // Conneting API to get CEP Values
    $http.get(`${API_URL}/carriers/correios/get-cep/${this.cep}`)
    .timeout(500, () => {
      .success((address) => {
        this.CEPloading = false;
        this.CEPerror = false;
        this.validCEP = true;

        updateShippingPrice(address.uf);
        updatePrice();

        this.bairro = address.bairro;
        this.cidade = address.cidade;
        this.endereco = address.end;
        this.uf = address.uf;

        updatePrice();
      })
      .error(() => {
        this.CEPloading = false;
        this.CEPerror = true;
      });
    })

  }
  • But the function .timeout is to end right, obviously when he finishes reading these 500, it will stop working if there is no refresh before this execution is over.

1 answer

1


according to the website of the Angularjs.

use a p/ http configurator.

example below.

$scope.method = 'GET';
$scope.url = ${API_URL}/carriers/correios/get-cep/${this.cep};
$scope.timeout = 10000; (miliseconds);

$http({method: $scope.method, url: $scope.url, cache:false, timeout = $scope.timeout}).then(function(response) {
          $scope.status = response.status;
          $scope.data = response.data;
        }, function(response) {
          $scope.data = response.data || "Request failed";
          $scope.status = response.status;
      });

reference: https://docs.angularjs.org/api/ng/service/$http

  • that’s what I did, and it worked, thanks !

Browser other questions tagged

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