离子2本地存储无法将检索到的值设置为变量 [英] ionic 2 local storage unable to set retrieved value to variable

查看:135
本文介绍了离子2本地存储无法将检索到的值设置为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将从.get函数检索到的值设置为在外部声明但不能这样做的变量。

I am trying to set the value retrieved from .get function into a variable declared outside but unable to do so.

var dt;
//retrieve
this.local.get('didTutorial').then((value) => {
  alert(value);
   dt = value;
})

console.log("Local Storage value: "+dt);

我能够为警报获得真实,但是为控制台获取未定义正在函数外打印的.log。

I'm able to get "true" for the alert, but getting "undefined" for the console.log that is printing outside of the function.


一种解决方法是我可以将所有剩余的代码放入.then函数中,但这样会非常混乱。

One workaround is that I can put all my remaining codes into the ".then function" , but that would be very messy.

更新(解决方案):

按照离子api( http://ionicframework.com/docs/v2/api/platform/storage/LocalStorage/ ),他们使用.get来检索值。

As per ionic api (http://ionicframework.com/docs/v2/api/platform/storage/LocalStorage/) , they use .get to retrieve values.

由于使用promises有自己的限制,使用以下内容:

Since using promises has it's own limitations, by using the following:

 constructor(navController) {
     this.navController = navController;
     this.local = new Storage(LocalStorage);
 }

和getItem函数,

and getItem function,

localStorage.getItem('didTutorial')

你将无需将所有内容放入回调方法就可以检索它。

You will be able to retrieve it without having to put everything into the callback method.

推荐答案

在这种情况下从localStorage包装器中读取是异步,这意味着传递给 this.local.get 的回调在调用 console.log <之后被称为 / code>。尝试在回调中放置 console.log ;它应该工作:

Reading from your localStorage wrapper in this case is asynchronous, which means that the callback passed to this.local.get gets called after your call to console.log. Try placing console.log inside your callback; it should work then:

// retrieve
this.local.get('didTutorial').then((value) => {
  alert(value)
  var dt = value
  console.log("Local Storage value:", dt)
})

另外,你会注意到我改变了你的 console.log 调用参数。那是因为 console.log 接受一个或多个参数,并且当你传入它们而不是连接它们时格式化得更好。只是专业提示。

Also, you'll notice that I changed your console.log call arguments. That's because console.log accepts 1 or more parameters, and formats them much more nicely when you pass them in instead of concatenating them. Just a pro tip.

这篇关于离子2本地存储无法将检索到的值设置为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆