0

I have an effect, where depending on what comes back in the data, I may wish to submit an extra action.

Using information from this post, I can return two actions via the following...

public getData$ = createEffect(() => this.actions$.pipe(
    ofType(myDataActions.getData),
    map(() => this.isPollingActive = true),
    mergeMap(() =>
      this.myService.getAllData()
        .pipe(
          tap(data => this.previousResultsTimeUtc = data.previousResultsTimeUtc),
          mergeMap(data => [
            currentDayActions.getCurrentShiftSuccess(data.currentDay),
            myDataActions.getDataSuccess(data)
          ]),
            catchError(err => of(myDataActions.getDataFail(err)))
          ))
    ));

However, ideally, I would sometimes just want to submit a single actions,

eg

    ...
      mergeMap(data => [
            if (data.currentDay !== undefined) // <-- how to do this
              currentDayActions.getCurrentDaySuccess(data.currentDay),

            myDataActions.getDataSuccess(data.data)
          ]),

So, I only want to submit the currentDayActions.getCurrentDaySuccess if I get the data.

Of course the above is incorrect syntax, but I cant quite see how to get this "if" inside of here.

Update

Very similar example of this is here

The effect trying to do the same thing is in feature1/state/feature1.effects.ts

halfer
  • 19,824
  • 17
  • 99
  • 186
peterc
  • 6,921
  • 9
  • 65
  • 131
  • Hmm.. Kinda confused here.. will `myDataActions.getDataSuccess` get dispatched as well even if data.currentDay is defined? – wentjun Oct 13 '19 at 03:52

1 Answers1

1

An if else statement would do the trick:

public continuePolling$ = createEffect(() =>
    this.actions$.pipe(
      ofType(
        feature1Actions.startPollSuccess,

        takeWhile(() => this.isPollingActive),
        mergeMap(() =>
          this.feature1Service.getData().pipe(
            delay(8000),
            tap(
              data =>
                (this.previousResultsTimeUtc = data.previousResultsTimeUtc)
            ),
            switchMap(data => {
              if (data.currentDay == undefined) {
                return [feature1Actions.getLibrarySuccess(data)];
              } else {
                return [
                  feature1Actions.getCurrentDaySuccess(data.currentDay),
                  feature1Actions.getLibrarySuccess(data)
                ];
              }
            }),
            catchError(err => of(feature1Actions.getLibraryFail(err)))
          )
        )
      )
    )
  );
timdeschryver
  • 14,415
  • 1
  • 19
  • 32
  • Thankyou for that, i could get that syntax to work! Now i need to study so i understand why (ie the actions in the lists) – peterc Oct 13 '19 at 22:09