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(...); } );
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});
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(); }
source share