2

In the below code I have used subscribe inside subscribe. This code works but the code structure is very bad. I would like to refactor this code using rxjs(forkjoin or mergemap).I'm not sure how to achieve this. Can someone help me with this? Any help is appreciated.

this.chapservice.cycle().subscribe((current) => {
      this.selectedCycleId = current.ratingCycleId;
      this.chapService
        .getChapterEvalWithSkills(
          this.activeUser.ipn,
          this.selectedRatingCycleId
        )
        .subscribe((response) => {
          console.log("response", response);
          if (response && response.length > 0) {
            this.chapterEvals = response;
          }
        });
      this.chapservice
        .getIsitEmployeeStatus(this.activeUser.ipn, this.selectedCycleId)
        .subscribe((sdpStatus) => {
          this.activeUserStatus = sdpStatus;
       if (this.activeUserStatus.statusDescription == 'SUBMITTED') {
                 //do something
            }
        });
    });
mohammed fahimullah
  • 485
  • 1
  • 4
  • 10

1 Answers1

2

You have to use combination of forkJoin and switchMap.

  • Why switchMap? - because you have dependent values that can fulfilled by sequential execution only.
  • Why forkJoin? - You can use either forkJoin or mergeMap here.

Code

this.chapservice.cycle().pipe(
  switchMap((current: any) => 
     forkJoin(
        this.chapService.getChapterEvalWithSkills(
           this.activeUser.ipn,
           this.selectedRatingCycleId
        ),
        this.chapservice.getIsitEmployeeStatus(this.activeUser.ipn, current.ratingCycleId)
     )
  )
).subscribe(([chapterEvals, sdpStatus]) => {
      console.log(chapterEvals, sdpStatus);
      if (chapterEvals && chapterEvals.length > 0) {
        this.chapterEvals = chapterEvals;
      }
      this.activeUserStatus = sdpStatus;
      if (this.activeUserStatus.statusDescription == 'SUBMITTED') {
             //do something
        }
    });
});
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299