-3
orderedAnalysis.forEach((analysis) => {
                this.analysisCenterService.getAnalysisDetails(analysis.id).subscribe(detail => {
                    analysis.detailed = detail;
                });
            });
console.log(orderedAnalysis[0]);

This is the result of the log statement: Log output

But when I log orderedAnalysis[0].detailed the result will be undefined.

Why does this happen and how do I do this propely?

geisterfurz007
  • 5,292
  • 5
  • 33
  • 54

1 Answers1

1

It happens because HTTP call is asynchronous. So your code would looks like this:

orderedAnalysis.forEach((analysis, i) => {                    
     this.analysisCenterService.getAnalysisDetails(analysis.id)
        .subscribe(detail => {
                    analysis.detailed = detail;
                    console.log(analysis);
        });
});

UPDATE:

You can use async operator to await result your API call:

 async fooFunction() 
 {
     orderedAnalysis.forEach((analysis, i) => {                    
        let result = await this.analysisCenterService.getAnalysisDetails(analysis.id);
        analysis.detailed = result;
     });
     console.log(orderedAnalysis);
 }

If return type of getAnalysisDetails is Observable, then you can convert to Promise using .toPromise method:

 let result = await this.analysisCenterService.getAnalysisDetails(analysis.id).toPromise();
StepUp
  • 36,391
  • 15
  • 88
  • 148