angularrxjs

How do I return two http requests sequentially in rxjs and use data from first in second call?


I've written a http function that works using switch map to get the value from one http request and use it as a parameter in the second, but how do I return not only the final http request but also the data from the first?

Here is my function:

      .post<RxObservable<unknown>>(
        `${this.nextApiEndpoint}ProgramReview/GetAssessmentQuestionNumber`,
        body,
        {}
      )
      .pipe(
        switchMap((data) => {
          return this.http.post<any>(
            `${this.nextApiEndpoint}ProgramReview/GetProgramReviewQuestion`,
            { studentId: args.studentId, questionId: data, programReviewId: args.programReviewId },
            {}
          );
        }),
        catchError((err) => {
          return err;
        })
      );
  }

I subscribe to is in the component and get the return data from the final http request, but I also want to pass the data from the first request to the subscribe in the component.


Solution

  • it could be a bit ugly, but you will have to remap the event from the second call

          .post<DataType>(
            `${this.nextApiEndpoint}ProgramReview/GetAssessmentQuestionNumber`,
            body,
            {}
          )
          .pipe(
            switchMap((data) => {
              return this.http.post<any>(
                `${this.nextApiEndpoint}ProgramReview/GetProgramReviewQuestion`,
                { studentId: args.studentId, questionId: data, programReviewId: args.programReviewId },
                {}
              ).pipe(map(secondCallResult => [data, secondCallResult])); //added this line
            }),
            catchError((err) => {
              return err;
            })
          );
      }