How to set a timeout to abort $ http.get () inside a factory or service?

I have the following getData(url) method in my factory that uses $http.get(url) to retrieve data from a URL

 angular .module('az-app') .factory('WebServiceFactory', function ($http, $q) { var WebServiceFactory = this; WebServiceFactory.getData = function (url) { var deferred = $q.defer(); $http.get(url) .then( function (response) { deferred.resolve({ data: response }); }, function (rejected) { deferred.reject({ data: rejected }); } ); //Promise to be returned return deferred.promise; } 

It works fine, but I need to cancel http.get and / or reject the promise so that I can display an error message from my controller that has this method:

 var getSpecialties = function (type) { doctorsCtrl.showLoading(); var url = "example.com"; WebServiceFactory.getData(url) .then( function (result) { doctorsCtrl.hideLoading(); var specialtiesArray = result.data.data; StorageFactory.specialties = specialtiesArray; doctorsCtrl.specialties = StorageFactory.specialties //I WANT TO TRIGGER THIS REJECTED FUNCTION when timeout time is finished }, function (rejected) { doctorsCtrl.hideLoading(); doctorsCtrl.showAlert(); } ); } 
+6
source share
1 answer

The $http accepts the timeout property in the config object, which responds to what you need. Check out the documentation , especially the part of the config object:

timeout - {number | Promise} - timeout in milliseconds or a promise that should interrupt the request when resolving it.

Also note that you are using promises in an inefficient way. The following is the promise of antipattern :

 WebServiceFactory.getData = function (url) { var deferred = $q.defer(); $http.get(url) .then( function (response) { deferred.resolve(...); }, function (rejected) { deferred.reject(...); } ); //Promise to be returned return deferred.promise; } 

You could simply:

 WebServiceFactory.getData = function (url) { return $http.get(url); } 

With a timeout of 3 seconds, it will be:

Services:

 WebServiceFactory.getData = function (url) { return $http.get(url, {timeout: 3000}); // <-- timeout applies ONLY for this call } 

Controller:

 WebServiceFactory.getData(url).then( function (result) { doctorsCtrl.hideLoading(); doctorsCtrl.specialties = StorageFactory.specialties = result.data; }, function (rejected) { doctorsCtrl.hideLoading(); doctorsCtrl.showAlert(); } ); 

Please note that you call hideLoading both in case of success and in case of error. You can call it once, in the final code handler:

 // ... .finally(function () { doctorsCtrl.hideLoading(); } 
+7
source

All Articles