问题
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