angular - Bir subscribe içinde başka bir subscribe'ı çağırmanın en iyi yolu nedir?


Bir API'yi iki kez çağırmam gerekiyor, önce anahtarı bulmak için ve sonra o anahtarla ilgili veriyi çıkarmak için.

Bunu bir subscribe içinde subscribe olarak yaparak yaptım ama bunun kötü bir programlama uygulaması olduğunu fark ettim. FlapMap'ler hakkında okudum ama henüz bunu düzgün bir şekilde uygulamayı başaramadım.

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

``

Cevap #1

Bunu dene:

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

Cevap #2

Genellikle rxjs operatörleri bu tür kullanım durumları için arkadaşınızdır.

Dokümanı burada bulabilirsiniz: https://rxjs-dev.firebaseapp.com/guide/operators

Bu durumda switchMap ve tap kullanmanızı öneririm

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