在订阅中调用订阅的最佳方式是什么?

时间:2019-10-17 07:49:13

标签: angular typescript angular8

我需要两次调用API,首先找到密钥,然后使用该密钥提取相关数据。

我这样做是通过订阅内部的,但是发现这是不好的编程习惯。我了解了关于flapMaps的信息,但尚未正确实现。

``打字稿

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]);
          }
        }
      });
    });

``

2 个答案:

答案 0 :(得分:4)

尝试一下:

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]);
      }
    }
});

答案 1 :(得分:3)

通常,rxjs运算符是您的此类用例的朋友。

在此处查找文档:https://rxjs-dev.firebaseapp.com/guide/operators

在这种情况下,我建议使用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();