After previously asking a question on handling promises multiple times in AngularJS (AngularJS handle calling promise multiple times), I am facing a new challenge. This time, I need to retrieve a list of cities, but encounter an exception.
Similar to how countries were handled in my previous question, cities can also be called multiple times. However, this time around, I must implement a caching mechanism to prevent redundant calls for the same city data. While the solution from my old question blocked multiple calls altogether, I now need to allow certain calls - specifically when requesting cities for a new country.
My current dilemma is as follows: How can I effectively cache cities data to avoid making repeated calls for the same information? Essentially, my function needs to differentiate between requests for cities of a new country versus those already cached.
Below is the snippet of my service:
var cityCache = {};
vm.getCities = function (countryCode) {
if (countryCode!=undefined && !cityCache[countryCode]) {
vm.cityPromise = $http({
method: 'POST',
cache: true,
url: API + '/api/Global/CountryCities',
data: {
"CountryCode": countryCode
}
}).then(function successCallback(response,countryCode) {
if (errorHandler(response.data)) {
console.log("cities come from ajax")
cityCache[response.config.data.CountryCode] = response.data;
console.log(cityCache)
return response.data
}
});
} else {
vm.cityPromise = $timeout(function () {//I use this to get promise object
return cityCache[countryCode]
}, 0)
console.log("cities comes from cache");
}
return vm.cityPromise;
}
To illustrate further, let's consider the following scenario: If the getCities function is called three times simultaneously with the following arguments - requesting cities in Germany, Ireland, and Germany once more - ideally, there should only be two network calls made. One for Germany and one for Ireland, effectively reducing redundancy.