Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a global http timeout in AngularJs

Tags:

angularjs

I know I can set a timeout each and every time:

$http.get('path/to/service', {timeout: 5000}); 

... but I want to set a global timeout to keep my code DRY.

like image 618
drew schmaltz Avatar asked Feb 22 '13 01:02

drew schmaltz


People also ask

Does angular http have timeout?

AngularJS $http had timeout option and it worked just great. Yup, Im aware of that.

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers.

What is timeout service in AngularJS?

This '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.

Is http request is synchronous or asynchronous in AngularJS?

The problem is as follows, $http. get is asynchronous, before the response is fetched, the function returns. Therefore the calling function gets the data as empty string.


2 Answers

This is possible with bleeding-edge angular.js (tested with git master 4ae46814ff).

You can use request http interceptor. Like this.

 angular.module('yourapp')   .factory('timeoutHttpIntercept', function ($rootScope, $q) {     return {       'request': function(config) {         config.timeout = 10000;         return config;       }     };  }); 

And then in .config inject $httpProvider and do this:

$httpProvider.interceptors.push('timeoutHttpIntercept'); 
like image 90
Gregy Avatar answered Sep 20 '22 20:09

Gregy


UPDATED: $http will not respect default setting for timeout set it in httpProvider (see the comments). Possible workaround: https://gist.github.com/adnan-i/5014277

Original answer:

angular.module('MyApp', [])   .config(['$httpProvider', function($httpProvider) {     $httpProvider.defaults.timeout = 5000; }]); 
like image 22
Stewie Avatar answered Sep 17 '22 20:09

Stewie