Ionic 4 - How to assign storage value to variable

Hello there!

I am building an app in which I store and retrieve items from a device’s local storage using the ionic storage package. I have no problems with storing items, but I am having trouble with retrieving the stored values and using them as a variable.

For example, say I have this item in storage:

person = {
name: "Angela",
age: "32"
}

this.storage.set("01", person);

I want to get this item from storage and display it to a html page like so:

<p> {{ person.name }} </p>
<p> {{ person.age }} </p>

To do this, I would need to assign it to a variable called “person” when the page loads.
If I were to use this.person = this.storage.get("01"), I have a blank page.
If I use this.storage.get("01").then(item => (this.person = item)), this.person is undefined.

How can I get the value of the stored item and assign it to a class variable?

Thanks in advance :slight_smile:

As you did:

Your problem is one of timing. It’s not easy to know when this.person will get defined when you do this. There are a myriad of ways to deal with this; my preferred one is to initialize all public properties of a controller at the point of declaration. So, at a bare minimum, the declaration of person should look like:

interface Person {
  name?: string;
  age?: string | number;
}

class Page {
  person: Person = {};
}

Another option would be to wall off everything in your template that references person inside:

<ng-container *ngIf="person"></ng-container>

Try this. person = this. storage.get (“01”)

And an if statement as @rapropos suggested

This will work and I have been using the same