簡體   English   中英

在訂閱中調用訂閱的最佳方式是什么?

[英]What is the best way to call subscribe inside a subscribe?

我需要調用 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]);
          }
        }
      });
    });

``

嘗試這個:

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

通常 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM