0

I have tested different solution such as adding map or switchMap but I'm lost, I still can't get the data out of the subscribe of the Service function.

I have the service function :

getAllExperiments (): Observable<Experiment[]> {
   return  this.http.get<Experiment[]>(this.urlEndPoint)
     .pipe(
       catchError(this.handleError<Experiment[]>('getExperiments', []))
     );

   }

and the call in the ngOnInit:

async ngOnInit() {
      await this.experimentService.getAllExperiments()
      .subscribe( response => {
        this.expTable = response
        this.expId = this.expTable.length;
        console.log(this.expTable, this.expId) //appears after the other console.log but with the values
      })
      console.log(this.expId) //appears first and undefined

      await this.experimentService.getExperiment(this.expId)
      .subscribe(response => {
        this.experiment = response
      });

      await this.compareService.getScore(this.expId)
      .then(response => {
        this.expScore = response;
      })

    }

  }

And obviously the function getExperiment with the ID doesn't work as well.

I know it should be able to work with a toPromise but I don't see how to use it here.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Skimar
  • 129
  • 2
  • 11
  • 2
    Move the calls that need `expId` *inside* the subscription callback. Or convert the observables to promises, rather than subscribing to them, if you want to `await` them. – jonrsharpe Dec 12 '19 at 09:57
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jonrsharpe Dec 12 '19 at 09:58

1 Answers1

3

1) ngOnInit is not async so remove await from file.

2) if you want to connet more request you should use forkJoin (example).

3) If you need data from first request use switchMap (exapmle)

this.service.methodA(paramA).pipe(
switchMap((resA)=>this.service.methodB(resA.paramB))
).subscribe((resB)=> {...});
Xalion
  • 623
  • 9
  • 27