[英]What is the best way to call subscribe inside a subscribe?
I need to call an API two times, first to find the key and then with that key extract the relevant data.我需要调用 API 两次,首先找到密钥,然后用该密钥提取相关数据。
I did this by subscribing inside a subscribe but found out it was bad programming practice.我通过在订阅中订阅来做到这一点,但发现这是不好的编程习惯。 I read about flapMaps but have failed to properly implement it properly yet.
我读到了flapMaps,但还没有正确地实现它。
``typescript ``打字稿
this.DrQue.clinicDoctorQueControllerFind('key', ({ "include": [{"relation":"patientQue"}] })).subscribe(data => {
this.drQue = data;
for (let i = 0; i < this.drQue.length; ++i) {
if (this.componentDr == this.drQue[i].name) {
this.indexDr = i;
i = this.drQue.length + 1;
}
}
this.patQue.patientQueCheckInControllerFind(this.drQue[this.indexDr].patientQue.id).subscribe(data => {
for (let count = 0; count < data.length; ++count) {
if (data[count].status == this.checkStatus){
this.checkInArr.push(data[count]);
}
}
});
});
`` ``
Try this:尝试这个:
this.DrQue.clinicDoctorQueControllerFind('key', ({ "include": [{"relation":"patientQue"}] }))
.pipe(
switchMap((data) => {
/**
* Here we manipulate our data
*/
this.drQue = data;
for (let i = 0; i < this.drQue.length; ++i) {
if (this.componentDr == this.drQue[i].name) {
this.indexDr = i;
i = this.drQue.length + 1;
}
}
/**
* Here we return new Observable stream
*/
return this.patQue.patientQueCheckInControllerFind(this.drQue[this.indexDr].patientQue.id);
})
).subscribe(data => {
/**
* Here we subscribe to the result and manipulate it
*/
for (let count = 0; count < data.length; ++count) {
if (data[count].status == this.checkStatus){
this.checkInArr.push(data[count]);
}
}
});
Generally rxjs operators are your friends for such use cases.通常 rxjs 运算符是此类用例的朋友。
Find doc here: https://rxjs-dev.firebaseapp.com/guide/operators在此处查找文档: https://rxjs-dev.firebaseapp.com/guide/operators
I would suggest using switchMap and tap in this case我建议在这种情况下使用 switchMap 并点击
this.DrQue.clinicDoctorQueControllerFind('key', ({ "include": [{"relation":"patientQue"}] })).pipe(
tap(data => {
this.drQue = data;
for (let i = 0; i < this.drQue.length; ++i) {
if (this.componentDr == this.drQue[i].name) {
this.indexDr = i;
i = this.drQue.length + 1;
}
}
}),
switchMap(data => this.patQue.patientQueCheckInControllerFind(this.drQue[this.indexDr].patientQue.id)),
tap(data => {
for (let count = 0; count < data.length; ++count) {
if (data[count].status == this.checkStatus){
this.checkInArr.push(data[count]);
}
})
).subscribe();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.