1

I would like to use return results from multiple api requests and reuse it as a parameter for the second api request and the second api request return a result i have to reuse in the third api request !

The problem is i only can return one api

const email = this.credentialsForm.controls['email'].value;


this.http.get('https://drupal_users/index/' + email).pipe(
        map(users => {
            console.log(users);
            const user = users;
            this.userId = user;
            return user;
        }),
        mergeMap(user => {

           const ObservateurCulture = this.http.get('https://index.php/drupal_users/culture/' + email).subscribe((culture: any) => {})

       // Here i wish to reuse "culture" data in another Api call and reuse result again of "Parcelles" api request
          const Parcelles = this.http.get('https://index.php/drupal_users/totherdata/' + culture);

            return forkJoin([ObservateurCulture, Parcelles]);
        }),
        take(1)
    ).subscribe(result => {
        console.log(result);
        this.loading.dismiss();

    });

1 Answers1

0

If you want to get only result from the last api, mergeMap is more than enough for all of the things.

However if you want all of the data combined from the all apis you have to use additionaly pipe and map

Here's the example snippet!

let userId = -1;
const email = 'test';

const getUser = (email) => rxjs.of(1)
const getCulture = (email) => rxjs.of('en-US')
const getData = (culture) => rxjs.of({
  data: {}
})

const getResultFromLastApi = (email) => {
  getUser(email).pipe(
    rxjs.operators.tap(userId => {
      userId = userId;
    }),
    rxjs.operators.mergeMap(userId => getCulture(email)),
    rxjs.operators.mergeMap(culture => getData(culture)),
    rxjs.operators.take(1)
  ).subscribe(result => {
    console.log(result);
  });
}

const getCombinedResult = () => {
  getUser(email).pipe(
    rxjs.operators.tap(userId => {
      userId = userId;
    }),
    rxjs.operators.mergeMap(userId => getCulture(email).pipe(rxjs.operators.map(culture => ({
      userId,
      culture
    })))),
    rxjs.operators.mergeMap(cultureAndUser => getData(cultureAndUser.culture).pipe(rxjs.operators.map(data => ({ ...data,
      ...cultureAndUser
    })))),
    rxjs.operators.take(1)
  ).subscribe(result => {
    console.log(result);
  });
}

getResultFromLastApi(email);
getCombinedResult(email);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>

Also

map(users => {
            console.log(users);
            const user = users;
            this.userId = user;
            return user;
        }),

I would use tap instead of map in this section as you are not transforming the data but causing some side-effect in the app ( assign userId somewhere in the app )

tap(userId => {
            console.log(userId);
            this.userId = userId;
        }),
Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50