Get the return value of a subscribe

0

I am using an Apirest and I have configured a .service file in Angular with Observables.

I need to get the value that the subscribe returns to be able to return it with a return but it always throws the return before I finish the http.service

getIdMyDirector(centroMiDirector): number {

this.userService.getIdMiDirector("miDirector", centroMiDirector).subscribe(
      idDirectorHttp =>  { this.idDirector = idDirectorHttp; }
      );

    return this.idDirector;
}
    
asked by Arkhan6 03.01.2019 в 15:05
source

2 answers

1

The answer may vary depending on what you want to do.

  • if it is for example method that is directly in the TS of the component you are working on and the variable you are going to use to show idDirector in HTML you could only delete the return.

    getIdMyDirector(centroMiDirector) { this.userService.getIdMiDirector("miDirector", centroMiDirector).subscribe(idDirectorHttp => {this.idDirector = idDirectorHttp});}
    
  • In case of being used to do some other process with the idDirector I recommend using Async - Await.

    async getAsyncData () {     this.asyncResult = await this.httpClient.get (this.url) .toPromise ();     console.log ('No issues, I will wait until promise is resolved ..');   }

More information on how to use Async and Await

    
answered by 03.01.2019 / 16:50
source
0

Operations in javascript or typescript are not done sequentially, therefore, you must do the return within the subscribe.

getIdMyDirector(centroMiDirector): number {
    this.userService.getIdMiDirector("miDirector", centroMiDirector).subscribe(
      idDirectorHttp =>  {
         this.idDirector = idDirectorHttp; 
         return this.idDirector;
    });
}
    
answered by 04.01.2019 в 12:51