Forgive me if this question seems simple or silly, but I find myself in a new scenario and need some guidance. In my AngularJS app, I have a service with 4 methods that share about 80% of the same functionality and code. I want to optimize this and make it more efficient. Here is a simplified version of my service:
.factory('townDataService', function ($http) {
var townList = {};
townList.getTownList = function () {
return $http({method: 'GET', url: '/api/country/cities'})
.then(function (response) {
// Formatting the response data here...
var returnArray = [];
// Looping through the countries
var JsonData = response.data;
for (key in JsonData['countries']) {
// Formatting code...
}
// End of repeated code
return returnArray;
});
};
townList.getCurrentTown = function (place) {
return $http({method: 'GET', url: '/api/country/cities'})
.then(function (response) {
// Formatting the response data here...
var returnArray = [];
// Looping through the countries
var JsonData = response.data;
for (key in JsonData['countries']) {
// Formatting code...
}
// End of repeated code
// Further working with the returnArray...
for (var i = 0; i < returnArray.length; i++) {
// Do something
}
return currentTown;
});
};
townList.getCurrentCountry = function (place) {
return $http({method: 'GET', url: '/api/country/cities'})
.then(function (response) {
// Formatting the response data here...
var returnArray = [];
// Looping through the countries
var JsonData = response.data;
for (key in JsonData['countries']) {
// Formatting code...
}
// End of repeated code
// Further working with the returnArray...
for (var i = 0; i < returnArray.length; i++) {
// Do something
}
return currentCountry;
});
};
return townList;
}
);
I realize that I am repeating the same $http 'GET' request and formatting code in each method, which is not efficient. What is the best approach to centralize this functionality in its own function so that the GET request is only made once, but each method still returns a promise? Should I store the results of the $http request in a variable and inject it into each method before formatting the data? Or should I utilize a $cacheFactory?
I apologize if my question is unclear, and I appreciate any help you can provide.
Thank you.