How to dispatch same action multiple times from ngrx effects

Viewed 2282

I want to dispatch an action multiple times from my effect, for that purpose i am using concatMap, but as i am dispatching same action, it gets cancelled by its next dispatch. Is there a way to dispatch an action, when its previous dispatch gets completed.

Below code will help to understand the problem better.

@Effect()
  setCategory$ = this.actions$
    .ofType(GET_SESSION_AD_SUCCESS)
    .concatMap((action: Action) => {

      const category = action.payload;
      const categoryPath = category.path;
      const categoryDispatchArray = [];

      categoryPath.forEach((path, index) => {
        categoryDispatchArray.push({
          type: GET_SUBCATEGORIES_BY_PARENT,
          payload: { categoryId: path.id, index }
        });
      })

      return dispatchArray;

}
2 Answers

You should use flatmap in this case. This should work :

@Effect()
setCategory$ = this.actions$
.ofType(GET_SESSION_AD_SUCCESS)
.map((action) => action.payload)
.flatMap((payload) => {

  const category = payload;
  const categoryPath = category.path;
  const categoryDispatchArray = [];

  categoryPath.forEach((path, index) => {
    categoryDispatchArray.push({
      type: GET_SUBCATEGORIES_BY_PARENT,
      payload: { categoryId: path.id, index }
    });
  })

  return dispatchArray;
}
Related