【发布时间】:2021-09-24 01:47:09
【问题描述】:
我试图在我的 Observable 函数中发送 httpclient,它会在没有 HttpClient Complete 的情况下运行。
这是一个用于重现的演示代码
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 }];
}
这是Student
export class Student {
age: number;
}
对于预期结果,console.log(res); 应该在console.log(result[0]); 之前返回。
我尝试了很多方法,例如.toPromise 和async await,但都没有成功。
您可以在下面创建一个测试版本:
https://stackblitz.com/edit/save-file-to-drive-7dawzd?file=src/app/app.component.ts
【问题讨论】:
标签: angular typescript rxjs observable httpclient