Get Int from Storage?

I’m having issues simply trying to retrieve from storage, can anyone help please,

@Injectable()
export class LocalData 
{
    getUsergroupId()
    {
        this.storage.get("usergroupId").then((value) => {
            return value;
        })
    }
}

and then calling it elsewhere,

if (this.localData.getUsergroupId() == 2)
{
    console.log("hit");
}

returns the error == cannot be applied to types void and number. If i change it to a number, it complains there’s no return value.

It seems that at the line above, the storage.get("usergroupId") returns void. Are you sure the entry "usergroupId"actually exists? Have you verified it via dev-tools?

Hmm, try to add a return in your function call like this:

getUsergroupId() {
    return this.storage.get("usergroupId").then((value) => {
        return value;
    });
 }

Notice the return before this.storage.get("usergroupId").then((value) => {

thanks, it was working, it was just being retrieved later than I expect.

When you get build errors, a common instinct is to think first “how can I make this error go away as quickly as possible?”.

That is bad. Don’t do that.

Your first thought should be “what is this error trying to tell me?”, and the answer is “Promises are not the same thing as what they resolve to”. storage.get() returns a Promise. @maninak thought “oh, this function isn’t returning anything, so let’s make it return something”. That would have made the build shut up, but not really gotten to the root of the issue.

The fundamental problem is that @diamond_dunn thought that the return value; statement would have made getUsergroupId() return value. It won’t and can’t. That’s the nature of asynchronous programming. So here’s what I would do:

getUsergroupId(): Promise<number> {
  return this.storage.get("usergroupId");
}

this.localData.getUsergroupId().then((gid) => {
  if (gid === 2) {
    console.log("hit");
  }
});
1 Like

Yup, totally missed that one, rookie mistake. It’s not as easy to debug code from the phone, not gonna lie. :slight_smile:

Thanks for the heads-up.