Jaspreet Singh
Jaspreet Singh

Reputation: 319

How to handle long response times in AngularJS $http?

I have a method that fetches some data from an API.

$http.get("https://httpstat.us/200?sleep=20000", header).then(
  function successCallback(response) {
    //logic
  },
  function errorCallback(response) {
    
  }
);

In certain test cases, the API takes forever to respond so I need a way to handle such cases. If the API is taking more than 10 seconds, I need to return some data. I tried adding a timeout to the request using the code below

$http.get("https://httpstat.us/200?sleep=20000", {timeout: 10000}).then(

But this just aborts the request and goes to the error callback. Is there another way to know if the request is taking forever to respond without actually timing out the request?

Upvotes: 1

Views: 1411

Answers (2)

svarog
svarog

Reputation: 9847

If you just need to run a function after some time have passed you can utilize $timeout. Pass the function you want to run to the $timeout with the time in milliseconds, it will return you a timer promise. If your $http calls resolves before the timeout just run $timeout.cancel(\[promise\]) and pass it your timer promise. This will cancel the inner timeout function call.

Example

var timer = $timeout(function() {
  console.log("this request is taking too long...")
  // tell the client it will take a while ...
}, 10 * 1000);

$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  then(function(response) {
    // handle successful response ...
    $timeout.cancel(timer); // about your timeout function call
  }, function(response) {
    // handle rejection ...
});

You can of course cancel your timeout in the finally clause. (Plunker)

If you don't feel like writing the same code for every function that wraps $http, consider using an interceptor.

Upvotes: 0

FitzChill
FitzChill

Reputation: 866

Short anwser no, there is no build in way to notify the http service listener that the request is long.

You could however build a deferred wrapper that encapsulate the http call in a defer so that you will be able to notify your listener if the service takes too long to respond but you will have to time it yourself.

take a look at this post where the author address a similar problem to yours

https://www.peterbe.com/plog/angularjs-$q-notify-resolve-local-get-proxy

Upvotes: 1

Related Questions