How do I assign a variable from localForage as I d

2019-06-21 04:31发布

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

2条回答
孤傲高冷的网名
2楼-- · 2019-06-21 04:57

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);
查看更多
做个烂人
3楼-- · 2019-06-21 04:59
$localForage.setItem('localSavedValue','SavedValue').then(function() {
        $localForage.getItem('localSavedValue').then(function(data) {
            console.log(data); 
        });
    });

https://github.com/ocombe/angular-localForage#configure-the-provider-

查看更多
登录 后发表回答