What is the best way to call subscribe inside a subscribe?

Viewed 274

I need to call an API two times, first to find the key and then with that key extract the relevant data.

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.

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

``

2 Answers

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.

Find doc here: https://rxjs-dev.firebaseapp.com/guide/operators

I would suggest using switchMap and tap in this case

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