I have a service that must return to me countries list. But I want to cache country values to a variable to prevent multiple ajax calls. I have created a promise object but my html must call this service multiple times. When i call the service, sometimes it returns from ajax first time after that it returns from cache, sometimes it retruns from ajax 3 times after that cache. How can I handle this?
Here is my service:
var vm = this;
vm.countries;
vm.getCountries = function () {
var q = $q.defer();
if (vm.countries === undefined) {
return $http({
method: 'POST',
cache: true,
url: API + '/api/Global/Countries',
}).then(function successCallback(response) {
if (errorHandler(response.data)) {
vm.countries = response.data;
q.resolve(response.data)
console.log("ajax")
return q.promise;
}
});
} else {
console.log("cache")
q.resolve(vm.countries)
return q.promise;
}
}
returnstatement in front of $http. You should also handle the error and return q.promise if errorHandler returns false.