How do I assign a variable from localForage as I do in localStorage?

徘徊边缘 提交于 2020-01-14 09:11:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!