1

Hello im new in typeScript and Angular. I need to get a value in storage, the storage.get return a promise, so i try:

getNomeUsuario():string{
    var that = this;
    this.storage.get('nomeUsuario').then(function(nome){
        that.nomeUsuario = nome;
    }.bind(this));
    return this.nomeUsuario;
}

The problem is that always return a undefined. I also get the same with an arrow function.

getNomeUsuario():string{
    this.storage.get('nomeUsuario').then((nome)=>{
        this.nomeUsuario = nome;
    });
    return this.nomeUsuario;
}

How can I return the nome value ?

Sorry about my English hehe

jeanfrg
  • 2,201
  • 1
  • 27
  • 38
Rodrigo Sene
  • 302
  • 1
  • 11
  • It's because `getNomeUsuario()` almost instantly returns the current value of `this.nomeUsuario`, before asynchronous `this.storage.get()` changes the `this.nomeUsuario` value. – kamyl Jul 29 '17 at 21:00

2 Answers2

1

Since this.storage.get("nomeUsuario") is asynchronous, there's no way the getNomeUsuario() method can return it's value without returning a Promise, so you'll need to do it like this:

getNomeUsuario(): Promise<string> {
  return this.storage.get("nomeUsuario");   
}

And handle the Promise where you call getNomeUsuario().

ps: you could also use an Observable, but it would add complexity without any benefits.

Lucas Moulin
  • 2,290
  • 3
  • 29
  • 38
0

this.storage.get('nomeUsuario') executes asynchronously, and when you returns that.nomeUsuario, the promise wasn't executed yet and that.nomeUsuario still undefined. Try to insert this return into .then section like this:

getNomeUsuario():string{
    var that = this;
    this.storage.get('nomeUsuario').then((nome)=>{
        that.nomeUsuario = nome;
        return that.nomeUsuario;
    });
}
Commercial Suicide
  • 14,875
  • 14
  • 62
  • 80