2

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 Answer 1

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;
});
Sign up to request clarification or add additional context in comments.

10 Comments

I've removed the .then((res...) because getInfo it's a void, It's returning undefined
Plus it's returning null because it does not return the value in .then condition from getInfo()
You've set the value stored at userInfo attribute inside .then() function.
ok I did a console.log(userInfo) and it shows the object, but I was looking for to get it from my service and from the splash get the info
@Stuart2041 If you need a synchronous way, I believe that you can't use this storage service
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.