How to set a timeout for a request?

Asked

Viewed 1,052 times

3

I’m making a requisition JSONP for a webservice. But sometimes the request takes too long. As I am showing the user a loading status, I would like to abort the request if it is more than 10 seconds.

How do I set a timeout for a request in Angularjs?

Example:

var url = "https://exemplo.com.br/" + $scope.consulta.cep + "/json/";

$http.get(url)
.then(function (response) {

   // faz o resto aqui
})
  • See, man, let me ask you something slightly out of context: you’re wearing styleguide?

  • Vixe, what is it?

  • It’s a good practice manual for programming in Angular. I wanted to have discovered this when I started learning: https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md

2 answers

3


You just put the setting timeout:

$http.get(url, {timeout: 10000})...

If you want to do it with promise:

var cancelar = $q.defer();

$http.get(url, {timeout: cancelar.promise})...

$timeout(cancelar.resolve, 10000);
  • Man, you won’t believe it. You don’t want to work! It seems like it’s really simple, but the bullshit hangs here and not for more.

  • I read about it here: http://stackoverflow.com/questions/24739988/abort-jsonp-request-angularjs. It seems that really, there is no way. Thank you for the reply.

  • That’s weird, I’m pretty sure I’ve used it before. I wonder if it just gives this problem to JSONP?

  • @Wallacemaxters Can try to do with the promise anything. If you want to mount an example

  • I think it is. I’m going to do a test. Instead of sending the request via JSONP, I’m going to do the server for WS, and Angular for the server.

  • It can be with Promise as well. The more the better :p

Show 1 more comment

2

Have you tried assigning the timeout in the Interceptor?

angular.module('app')
  .factory('timeoutInterceptor', function ($rootScope, $q) {
    return {
      'request': function(config) {
         url = config.url; 
         if (url == "myUrl") { config.timeout = 10000; } 
        return config;
      }
    };
 }); 

In config...

$httpProvider.interceptors.push('timeoutInterceptor');
  • Um... In the Interceptor this timeout would be standard for all requests.

  • If you need to treat this condition only for a specific request apply the timeout only to it. Ex: var url = config.url; Function(config) { if (url == "myUrl") { config.timeout = 10000; } Return config; }

Browser other questions tagged

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