I asked this question before (AngularJS handle calling promise multiple times) and now I have different obstacle. Now I have to get cities list but there is an exception.
Cities can be called multiple times like countries (in my old question) and I have to cache data to prevent multiple calls for same data(cities). Old question's solution can block multiple calls but now I have to let some calls (for new country's cities).
So my question is: How can I cache cities data to prevent call for same data? (My function have to catch if call is for new country's cities list or not. if yes: call service and get cities, if not: return cities from cache)
Here is 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;
}
Example:
Let's say I am calling getCities function 3 times in the same time. I am watching my network traffic via chrome. I see 3 ajax calls. It's normal. But sometimes, I call for same city. I need to edit my function that can understand if city data is already called before (kind of cache).
For example: If i ask function 3 times with this arguments:
1-Give me the cities in Germany,
2-Give me the cities in Ireland,
3-Give me the cities in Germany (again),
It's calling 3 times. But I want 1 call for Germany, 1 call for Ireland. Just 2 calls.