Angular NgRx - dispatch an action from effect when other actions return a value

Viewed 199

I'm having trouble dispatching actions that needs results from other five actions (that are listed in my effect).

Can somebody help me with this? To recap, I need to dispatch an action inside effect once these five actions have given back a value.

Here is the code after which I'd like to call getProject():

    getProjectRefData$ = createEffect(() =>
    this.actions$.pipe(
      ofType(GetProjectRefData),
      mergeMap(() =>
        of(
          GetProjectSubTypes(),
          GetAccountCategories(),
          GetProductions(),
          GetCompetitions(),
          GetCompetitionEditions()
        )
      )
    )
  );

And here is the blueprint example of each of those five actions (or rather, effects they are triggering):

    getCompetitionEditions$ = createEffect(() =>
    this.actions$.pipe(
      ofType(GetCompetitionEditions),
      mergeMap(() =>
        this._factoryService
          .getFactory('/referencedata/competitioneditions')
          .pipe(
            map((res: ICompetitionEdition[]) =>
              GetCompetitionEditionsSuccess({ payload: res })
            ),
            catchError(err => {
              console.error(err);
              return of(
                OpenSnackBar({
                  payload: {
                    type: 'error',
                    message: JSON.parse(err._body).message,
                    id: uuid.v4(),
                  },
                }),
                GetCompetitionEditionsError()
              );
            })
          )
      )
    )
  );
1 Answers

Go for forkJoin:

   getProjectRefData$ = createEffect(() =>
    this.actions$.pipe(
      ofType(GetProjectRefData),
      switchMap(action =>
        forkJoin(
          GetProjectSubTypes(),
          GetAccountCategories(),
          GetProductions(),
          GetCompetitions(),
          GetCompetitionEditions()
        )
      ),
      map(([projectSubtypes, accountCategories, productions, competitions, competitionEndings]) => this.someService.get('pass args here'),
      map(callResult => SomeAction(callResult))
    )
  );

forkJoin will emit a combined value in a form of an array after all of inner observables complete.

Related