craquito
craquito

Reputation: 11

Angular, extract the value from a promise

I have a function that returns a Promise and inside that Promise I get an object in the resolve. Here it is the function of my service that works good.

buscarUsuario(email: string){
return new Promise((resolve, reject) => {
  this.http.post(`${URL}/user/email`, {email})
           .subscribe(resp => {                     
           //console.log(resp['usuario']);
           
           resolve(resp['usuario']);
          }); 
}) 

}

And then I get the value from the promise in this var:

const getDatos = this.usuarioService.buscarUsuario(this.correoUsuario.value.toString());

And then I call the var to get the value from the resolve and I can't extract that value from there:

var usuario: Usuario;
getDatos.then(usu => {
 
      usuario = usu;
      //Here I can see the value
      console.log(usuario);
      
    });
//But here I can't see the value
//And it's where I really need to get the value
console.log(usuario);

So, how do I get that value outside the Promise?

Upvotes: 0

Views: 75

Answers (2)

Owen Kelvin
Owen Kelvin

Reputation: 15083

Using Promises in Angular is NOT recommended. Angular recommends use of Observable to handle asynchronous operations

Lets Try and change your code to return Observables only

buscarUsuario = (email: string)  =>
  this.http.post<any>(`${URL}/user/email`, {email}).pipe(
    map(resp => resp.usuario as Usuario)
  )

Basically the above code returns an Observable<any>(Observable of type any). I have type casted using <any> to transform the result to an Obserable<any>. Next I have use piping to extract the usuario from response

Now we can actually assign this value to a variable...

const getDatos$ = this.usuarioService.buscarUsuario(this.correoUsuario.value.toString());

NOTE: This is an Observable and you will need to subscribe to it

Observable can be assigned like any other property

const usuario: Observable<Usuario> = getDatos$

Upvotes: 1

indsoft
indsoft

Reputation: 83

You cannot get the value outside that function, reason because since you use promise, you need to wait until the promise returns the value, so best possible way is you have do rest of your functionality within promise.then.

getDatos.then(usu => {
  //implement your other functionality
});`

  

Upvotes: 0

Related Questions