Akki
Akki

Reputation: 1778

How to call inter dependent Httpservice Calls using RxJS Firstvaluefrom?

I am new to NestJS, There is one scenario, where I need to call 2 Httpservice calls in a Service File. First call is POST call which returns some data and I want to use that returned data in a second http GET call. I am using Axios httpsevice and firstvalufrom(RXJS) with simple map as shown below:

const response1 = await firstValueFrom(
        this.httpService.post(URL, body, headers).pipe(
          map((response: AxiosResponse<any>) => {
            return response.data //this data is needed for subsequent GET call
          }),
        ),
  );
const header2 = { 
                   "content-type":"application/json", 
                   params: {data: response1.data} // response1 data is used here
                }
const response2 = await firstValueFrom(
        this.httpService.get(URL, headers2).pipe(
          map((resp2: AxiosResponse<any>) => {
            return resp2.data
          }),
        ),
  );

I have written this 2 calls sequentially but it is possible that code may run asynchronously and second http GET call may get executed before POST call 1 which may result in error because GET call 2 is dependent on call 1 response.

I am thinking of using concatMap but not getting proper example so Please let me know the solution for this issue

Upvotes: 0

Views: 457

Answers (1)

Matthieu Riegler
Matthieu Riegler

Reputation: 55450

Yeah switchMap or similar is the way to go !

  this.httpService.post(URL, body, headers)
    .pipe(
      switchMap((response: AxiosResponse<any>) => {
        const headers2 = {
          "content-type": "application/json",
          params: { data: response.data } // response1 data is used here
        }
        return this.httpService.get(URL, headers2);
      }),
      map((resp2: AxiosResponse<any>) => {
        return resp2.data
      }),
    )

Upvotes: 2

Related Questions