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?
CodePudding user response:
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.
CodePudding user response:
Simply you can continue writing the next call after you finished the first one (someValue.forEach).
The long scenario is:
- Call the action "someOtherAction".
- Create a Reducer that reads the array and update the Store with it.
- Create a Selector that reads the array from the Store.
- In the Component you subscribe on the Selector.
- Inside the Subscribe event you Dispatch a new Action that call the second call you mentioned. For inspiration, you can read this example in gitHub: https://github.com/DeborahK/Angular-NgRx-GettingStarted/tree/master/APM-Demo5/src/app/products/state