问题
Please help me with the following.
I have been converting my AngularJS application from localStorage to localForage.
throughout my application I was assigning the localStorage value like this.
window.localStorage.setItem('localSavedValue','SavedValue');
and then I was retrieving the data like this,
var myValue = window.localStorage.getItem('localSavedValue');
So when I console.log(myValue); // it outputted 'SavedValue'
I cannot seem to do this with localForage when I try,
$localForage.setItem('localSavedValue','SavedValue');
var myValue = $localForage.getItem('localSavedValue');
console.log(myValue); // returns an object.
I don't get the value set to myValue.
I am sure this is something do do with promises as when I use the callback I can access the correct 'myValue' however I want to get it out of the call back to use in the rest of the service.
Also to note, I am in a service so can't assign to $scope (unless I don't know how).
Appreciate any help.
Thanks B
回答1:
$localForage.setItem('localSavedValue','SavedValue').then(function() {
$localForage.getItem('localSavedValue').then(function(data) {
console.log(data);
});
});
https://github.com/ocombe/angular-localForage#configure-the-provider-
回答2:
LocalForage is async by design so I would suggest you to use Promises like @RouR suggested.
A minor improvement for code clarity would be to chain-return the promise results, but you still can't avoid the async code consequences.
$localForage.setItem('localSavedValue','SavedValue').then(function() {
return $localForage.getItem('localSavedValue');
}).then(function(data) {
console.log('I\'m printed second', data);
});
console.log('I\'m printed first');
If you are using Babel, a more friendly approach for such migrations would be to configure it to use transform-async-to-generator or preset-es2017 and rewrite such code as
await $localForage.setItem('localSavedValue','SavedValue');
const data = await $localForage.getItem('localSavedValue');
console.log(data);
来源:https://stackoverflow.com/questions/28388850/how-do-i-assign-a-variable-from-localforage-as-i-do-in-localstorage