How to set a timeout for a request?

3

I am making a JSONP request for a webservice. But sometimes the request takes too long. Since I am showing the user a load status, I would like to abort the request if it passes 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
})
    
asked by anonymous 18.11.2016 / 13:31

2 answers

3

You just put the timeout :

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

If you want to do it with a promise:

var cancelar = $q.defer();

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

$timeout(cancelar.resolve, 10000);
    
18.11.2016 / 13:33
2

Have you tried assigning timeout to 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;
      }
    };
 }); 

No config ...

$httpProvider.interceptors.push('timeoutInterceptor');
    
18.11.2016 / 14:00