0

I am trying to query database. Iterate over list of results and for each item execute one more request. At the end of rxjs construction I have Observable<Observable<Timesheet>[]>. But I need to have Observable<Timesheet[]>. How to do that?

this.caseService.getElapsedCases(date).pipe(
  map(elapsedCases => elapsedCases.map(elapsedCase => {
    return this.caseService.findOneById(elapsedCase.caseId).pipe(
      map(loadedCase => {
        const timesheet: Timesheet = {
          id: elapsedCase.id,
          start: elapsedCase.start,
          end: elapsedCase.end,
          case: loadedCase,
          isActive: false
        };

        return timesheet;
      })
    );
  }))
);

2 Answers 2

1

You need to forkJoin separate requests and mergeMap to source:

const loadElapsedCase: Observable<TimesheetEnt[]> = getElapsedCase().pipe(
  mergeMap(elapsedCases => elapsedCases.map(elapsedCase => {
    return forkJoin(findOneById().pipe(
      map(loadedCase => {
        return {
          id: elapsedCase.id,
          title: elapsedCase.title,
          case: loadedCase
        };
      }))
    );
  }))
);
Sign up to request clarification or add additional context in comments.

Comments

0

Use mergeMap + forkJoin! mergeMap combines the values emitted by multiple Observables into one Observable. forkJoin allows you to wait for the result of a list of Observables and combine the results of all those Observables as a list (comparable to Promise.all). See: https://rxmarbles.com/#mergeMap and https://rxmarbles.com/#forkJoin

Thanks to the answer of ritaj I learned it should be forkJoin. This works:

const loadElapsedCase: Observable<TimesheetEnt[]> = getElapsedCase().pipe(
  mergeMap(elapsedCases => 
    forkJoin(
      elapsedCases.map(elapsedCase => {
        return findOneById().pipe(
          map(loadedCase => {
            return {
              id: elapsedCase.id,
              title: elapsedCase.title,
              case: loadedCase
            };
          })
        );
      })
    )
  )
);

In the StackBlitz: https://stackblitz.com/edit/rxjs-zidltc?file=index.ts

4 Comments

It is not working. Unfortunately type of result for first solution is Observable<Observable<Timesheet>> and not Observable<Timesheet[]>. Second options is not compiled because elapsedCase is not defined
thanks for helping, please check : stackblitz.com/edit/rxjs-dapk33
Your stackblitz is now just the rxjs playground. You probably need to save your changes.
sorry, check it now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.