D
D
Drovosek012021-10-22 07:40:54
JavaScript
Drovosek01, 2021-10-22 07:40:54

How to execute 2 requests in a row in rxjs and process the results of only the first one?

There are 2 requests for the backend. To execute the second query, you need the result of the first query.
After executing both requests, you need to execute the function, into which you need to pass again the results of the first request.

Now it looks something like this:

this.profileDocumentService.getDataOne(profileId, identityTranslationCreateContract).pipe(
  tap((someDataFromOne) => {
    if (someDataFromOne.document) {
      this.documentApiAdapter.getDataTwo(translationResponse.id as number, someDataFromOne.document).subscribe();
    }
  }),
  map((someDataFromOne) => this.mapIdentityTranslationDocument([someDataFromOne]))

but this is wrong, because inside an Observable it is not allowed/very_bad to subscribe to another Observable.

How to make such a request correctly, without subscriptions inside the subscription, and so that in the callback inside the map you can take the results of the first request?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Drovosek01, 2021-11-03
@Drovosek01

In general, I solved the problem with this design. Maybe it will help someone:

this.profileDocumentService.getDataOne(profileId, identityTranslationCreateContract).pipe(
      switchMap((previousFioResponse) => {
        if (previousFioResponse.document) {
          return this.documentApiAdapter
            .getDataTwo(previousFioResponse.id, previousFioDocument.document)
            .pipe(map(() => this.mapPreviousFioDocument([previousFioResponse])));
        }
        return of(this.mapPreviousFioDocument([previousFioDocument]));
      })
    );

N
Nadim Zakirov, 2021-10-22
@zkrvndm

In order not to clutter up the code with callbacks, there are promises, use them.

L
lssssssssssl, 2021-10-22
@lsssssssssl

If only .subscribe() confuses you, do
await firstValueFrom(this.documentApiAdapter.getDataTwo(translationResponse.id as number, someDataFromOne.document)) and don't rack your brains.
rxjs7+. Self signing, self unsubscribing.
https://rxjs.dev/api/index/function/firstValueFrom

V
Vitaly Kadyrov, 2021-11-01
@Ahmad66617

As it was correctly said above - about callbacks, for example, and a car of checks on if-s - look towards exchaustMap - I use it myself - in NgRx effects - when you need to wait for the result from the back and then do something

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question