我如何在localStorage中分配localForage中的变量? [英] How do I assign a variable from localForage as I do in localStorage?
问题描述
请帮我解决以下问题。
Please help me with the following.
我一直在将我的AngularJS应用程序从localStorage转换为localForage。
I have been converting my AngularJS application from localStorage to localForage.
在我的应用程序中我分配了localStorage像这样的价值。
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');
所以当我在console.log(myValue)时; //输出'SavedValue'
So when I console.log(myValue); // it outputted 'SavedValue'
我尝试使用localForage时似乎无法做到这一点,
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.
我没有将值设置为myValue。
I don't get the value set to myValue.
我确信这是与promises有关的事情,因为当我使用回调时我可以访问正确的'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.
另外要注意,我在服务中因此无法分配到$ scope(除非我不知道如何)。
Also to note, I am in a service so can't assign to $scope (unless I don't know how).
感谢任何帮助。
谢谢
B
推荐答案
LocalForage在设计上是异步的,所以我建议你使用像@RouR建议的Promise。
LocalForage is async by design so I would suggest you to use Promises like @RouR suggested.
代码清晰度的一个小改进是链 - 返回promise结果,但你仍然无法避免异步代码的后果。
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');
如果您使用的是Babel,这种迁移的更友好方法是将其配置为使用< a href =https://babeljs.io/docs/plugins/transform-async-to-generator/\"rel =nofollow noreferrer> transform-async-to-generator 或 preset-es2017 并重写代码为
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);
这篇关于我如何在localStorage中分配localForage中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!