ionic 2 local storage unable to set retrieved value to variable

早过忘川 提交于 2019-12-23 17:14:22

问题


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);

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

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

Update(Solution):

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

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

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

and getItem function,

localStorage.getItem('didTutorial')

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


回答1:


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)
})

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.



来源:https://stackoverflow.com/questions/36831634/ionic-2-local-storage-unable-to-set-retrieved-value-to-variable

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