wonder95 wonder95 - 2 months ago 6
Javascript Question

Return promise from service for locally stored data in angular

I have some config data for my app that is stored on my API server (form.io in this case), and since it will be rarely changed, I want to store it in localStorage and then update it as needed. So in my getStationConfig service, I check for the data in localStorage, and if it's not there, get it from the API and store it locally for next time.

The issue is returning the data from localStorage in a promise so my controller code that is expecting a promise can handle it. The code to get the data from my controller is this:

var stationPromise = shiftService.getStationConfig().then(function(data) {
vm.configSlots = data;
});


and my service looks like this:

var getStationConfig = function() {
// First check to see if info is stored locally.
var config = JSON.parse(localStorage.getItem('cfdConfig'));
if (config) {
return config;
}

// Get position info from appropriate Config resource submission.
// Code borrowed 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) {
// Code goes here to format the data for return to the controller

// Now that it's all formatted, store the info in localstorage so that it can be retrieved from there
// later and we don't have to keep hitting the API for it.
localStorage.setItem('cfdConfig', JSON.stringify(allSlots));

return allSlots;
},
function(err) {
console.log(err);
});
};


As is is written, the data that is returned from localStorage (the config var at the top) is in the same format as allSlots at the bottom, but it's not in a promise, so the controller doesn't like it. How can I wrap or return it so that it's in a promise? Do I need to just call localStorage via $http.get() (if that's possible)? Or another way?

Thanks.

Answer

Inject $q promise service into your service and use it to return the data wrapped in a promise

if (config) {
  return $q.resolve(config);
}