Attempting to send HttpClient in an Observable function without waiting for it to complete.
Below is a sample code snippet to replicate the issue:
test() {
this.test2()
.pipe(
mergeMap((result) => {
console.log(result[0]);
return of([]);
})
)
.subscribe();
}
test1(): Observable<any> {
return of(this.getStudents());
}
test2(): Observable<any> {
return this.test1().pipe(
mergeMap((result) => {
if (result) {
result.map((rr) => {
if (rr.age == 1) {
this.client
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.subscribe((res) => {
console.log(res);
rr.age = rr.age * 10000;
});
} else {
rr.age = rr.age * 10;
}
return rr;
});
}
return of(result);
})
);
}
getStudents(): Student[] {
return [{ age: 1 }, { age: 2 }, { age: 3 }];
}
This is Student
export class Student {
age: number;
}
To achieve the expected result, console.log(res);
should come before console.log(result[0]);
.
Tried methods like .toPromise
and async await
, but didn't succeed in resolving the issue.
You can try out a modified version here:
https://stackblitz.com/edit/save-file-to-drive-7dawzd?file=src/app/app.component.ts