Sam Sam - 4 months ago 17
Ajax Question

AngularJS handle calling promise multiple times

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;
}
}

Answer

You can cache the promise instead of the data. You may also want to consider what would happen in the error case here. The cached promise would need to be cleared.

var vm = this;

function getCountries () {
    if (!vm.countryPromise) {
        vm.countryPromise = $http({
            method: 'POST',
            cache: true,
            url: API + '/api/Global/Countries',
        }).then(function successCallback(response) {
            if (errorHandler(response.data)) {
                console.log("ajax")
                return response.data;
            }
        });
    } else {
        console.log("cache")
    }
    return vm.countryPromise;
}