Eric Cheng
Eric Cheng

Reputation: 517

how to call API based on another API result?

In React-Redux Epic, I am trying to call get method 1, and then call get method 2 based on the first method1's result.

export const testEpic = (action$, state) => {
   return merge(

      action$.pipe(
         ofType(EpicTypes.API1),
         map((action) => {
            const api1Url = `http://10.1.2.345/api1`;
            return ajax.getJSON(loginUrl);
         }),
      ).pipe(
         map((result1) => {
            console.log(`api1 result:`, result1);   // result1 is 
            const {id} = result1;
            const api2Url = `http://10.1.2.345/api2/${id}`;
            return ajax.getJSON(api2Url)
         }),
      ).pipe(
         mpa((result2) => { ....... }
..........

I expected to call api1, the result1 goes to the second map, and then call api2 with result1, and the get the result2. However, seems api1 result I got is observable. What should I do to get result1 and make another api call base on it?

Upvotes: 0

Views: 70

Answers (1)

Picci
Picci

Reputation: 17762

Substitute map With concatMap and you should get what you want. The reason is that functions like concatMap (or switchMap mergeMap) receive an Observable in input, which they internally subscribe to, and return a new Observable which can be subscribed. In this way, when the last Observable is subscribed to, first the first one is executed and its result can be used by the second one.

Upvotes: 1

Related Questions