My application's configuration data is stored on an API server (specifically, form.io) and since it will rarely be changed, I have decided to store it in localStorage. To achieve this, I check for the data in localStorage within my getStationConfig service. If the data is not found locally, I fetch it from the API and save it locally for future use.
The challenge lies in returning the data from localStorage as a promise so that it can be handled by my controller code which is expecting a promise. The snippet of code used to retrieve the data in the controller looks like this:
var stationPromise = shiftService.getStationConfig().then(function(data) {
vm.configSlots = data;
});
Here is how my service is structured:
var getStationConfig = function() {
// Check if information is stored locally.
var config = JSON.parse(localStorage.getItem('cfdConfig'));
if (config) {
return config;
}
// Retrieve configuration info from the appropriate Config resource submission.
// Code adapted from ngFormioHelper.FormioAuth.
var token = localStorage.getItem('formioToken');
var config = {
disableJWT: true,
headers: {
"x-jwt-token": token
}
};
return $http.get(Formio.getAppUrl() + '/config/submission', config)
.then(function(result) {
// Format the data before returning it to the controller
// Store the formatted info in localStorage to reduce calls to the API
localStorage.setItem('cfdConfig', JSON.stringify(allSlots));
return allSlots;
},
function(err) {
console.log(err);
});
};
While the data returned from localStorage is in the same format as 'allSlots' at the end, it is not wrapped in a promise causing issues with the controller. I am seeking advice on how to wrap or return it as a promise. Should I try calling localStorage via $http.get() or explore another approach?
Thank you.