首页 文章

存储不返回离子串

提问于
浏览
2

我已经实现了Storage for Ionic(不需要新的东西来存储值) .

我已经创建了一个存储 object 的服务(它有效,因为我有console.logged()它),但是当我想 get() 时,当我使用相同的密钥时它会返回 undefined ,即使 console.log() 来自 get() 方法打印出我想要的东西......

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

它正在返回 null 因为我添加了 var vall = null 并且看起来它没有改变任何东西......

我这样存储:

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

我想要得到这样的信息:

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

我错过了什么?

1 回答

  • 1

    发生这种情况是因为存储方法是异步的,并且返回时值为null .

    你能这样试试吗?

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

    并获取信息:

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

相关问题