Storage not returning string ionic

我的未来我决定 提交于 2019-12-12 20:47:45

问题


I've implemented Storage for Ionic (don't know if it's something new to store values).

I've created a service that stores an object (it works, because I've console.logged() it), but when I want to get() it's returning me undefined when I use the same key, even when the console.log() from the get() method prints what I want...

getInfo(keystorage): string {
    var val = null;  
        this.storage.get(keystorage).then((profile) => {
            val = JSON.parse(profile);
            console.log(val["info"]); //returning what I want
            return val["info"];
        })
        .catch((err: any) => {
            return 'catchhhh';
        });
        return val;
    }

It's returning null now because I've added var vall = null and looks like it doesn't change anything...

I store it like this:

saveInfo(usr){
    if(usr==null) return;
    var usertostore = {"id": currentUser["id"], "info":currentUser["info"]};
    this.storage.set("userLoged",JSON.stringify(usertostore ))
  }

I'm trying to get the info like this:

var userInfo = this.storageService.getInfo('myKey');

What am I missing?


回答1:


This happen because the storage method is asynchronous and the value is null when it is returned.

Can you try this way?

getInfo(keystorage) {
    return this.storage.get(keystorage);
}

saveInfo(usr){
    if(usr==null) return;
    var usertostore = {"id": 1234, "info":"fdsgf"};
    this.storage.set("userLoged",JSON.stringify(usertostore ))
}

and get the info:

getInfo('userLoged').then((res) => {
  var userInfo = res;
});


来源:https://stackoverflow.com/questions/44804692/storage-not-returning-string-ionic

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