3

As said in the title my problem is when I do:

this.storage.get('user')

I get this object

t {__zone_symbol__state: null, __zone_symbol__value: Array(0)}

and I don't know how to manipulate it.

I'm asking if there is a way to get a string value from my storage example

// when i store user id like that 
this.storage.set("user", JSON.stringify(userID));
console.log(this.storage.get('user'))//output 100 for example
pirho
  • 11,565
  • 12
  • 43
  • 70

2 Answers2

7

The accepted answer certainly works. Since follow-up comments are asking about how to use the resulting string from storage, an alternative is to use async/await to deal with the promises. That can clean up the potential mess of nested .then()'s

let result: string = await this.storage.get('user');
//Use result here
BRass
  • 3,698
  • 2
  • 28
  • 46
  • hi, thanks for your help, is there a specific way to use this line of code like inside a method or something because when i use it directly like that it gives me this error `Typescript Error Cannot find name 'await'.` and `Typescript Error ',' expected. after await` – khaled djellal Feb 23 '18 at 08:05
  • 1
    Typescript added support for `async/await` in 1.7. An `await` needs to be inside a method marked with `async`. See the typescript 1.7 docs for more info: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-7.html – BRass Feb 23 '18 at 15:04
  • thank you, i did it as u said and it works now i have a second question if you allow me of course, is there a way to make a global variable and when ever i want to use the value i got from my storage all i have to do is using that variable? – khaled djellal Feb 23 '18 at 15:41
  • Possible, yes. You could make a property off an Angular service/provider, which gets populated (at startup?) from this async storage method. The down side is the property will be null/empty until the async startup routine populates it. Not much you can do there since getting things from storage is async and uses promises - you can't really force it into a simple variable. – BRass Feb 23 '18 at 17:17
  • hmmm thank you so the provider thing will be more for reducing line of codes and make it easier to manipulate – khaled djellal Feb 23 '18 at 20:16
5

Ionic storage returns a promise of the data. So, you have to wait for the promise to get resolved and get the data like below:

this.storage.get('user').then((result) => {
      console.log('My result', result);
});
Setu Kumar Basak
  • 11,460
  • 9
  • 53
  • 85
  • it works for me like that, i have another question if possible if i have some treatment depending on that result all i have to do is to place it here ? `this.storage.get('user').then((result) => { // my code });` – khaled djellal Feb 22 '18 at 14:17
  • If it works like that, then you can accept the answer. And can you please elaborate the second question? – Setu Kumar Basak Feb 22 '18 at 14:22