I have the following method getData(url)
in a my factory which uses $http.get(url)
to get data from an 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 abort the http.get and/or reject the promise so I can display an error message from my controller which 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();
}
);
}
The service
$http
accepts, in the config object, atimeout
property that answers to what you need. Have a look at the documentation, especially the part about theconfig
object:Also, notice that you're using promises in an inefficient way. The following is a promise antipattern:
You could have simply:
With a timeout of 3 seconds it would be:
Service:
Controller:
Notice also that you're calling
hideLoading
both in case of success and error. You can call it once, in a chained finally handler: