Search code examples
angularrxjsngrxngrx-storengrx-effects

How do you combine RxJs and NgRx to make multiple Rest-Calls and make them wait for a result?


In my Effect im listening on an Action, that value of the Action is a string Array. Now i need to loop over the array and use the values as inputs for the next asnyc function.

someEffect$ = createEffect(() => 
    this.action$.pipe(
        ofType(someAction),
        mergeMap(({ someValue }) => 
            this.httpCall.getSomeTh(someValue[0]).pipe(
                map((result) => someOtherAction)
            )
        )       
    )
)

I have tried a few different things. The one below seemed to get me to the closest one i wanted. But since the Rest-calls need a moment to return, the array is always empty.

someEffect$ = createEffect(() => 
    this.action$.pipe(
        ofType(someAction),
        mergeMap(({ someValue }) => {
              const array = [];
              someValue.forEach((value) => 
                 this.http.get(value).pipe(tap((object) => array.push(object)))
              )

              return of(someOtherAction(array))
            }
        )       
    )
)

Does anyone have an idea, how to make the whole thing wait for the rest calls to return back?


Solution

  • Use a forkJoin.

    someEffect$ = createEffect(() => 
        this.action$.pipe(
            ofType(someAction),
            mergeMap(({ someValue }) => 
              forkJoin(someValue.map(value => this.http.get(value)))              
            )       
        )
    )
    

    The forkJoin takes an array of Obserables and emits when every Observable is completed. It outputs the results as an array.