NgRx-可选地从效果中返回一个或两个动作

时间:2019-10-13 03:29:38

标签: angular ngrx ngrx-effects

我会起作用,根据数据返回的内容,我不妨提交额外的操作。

使用this post中的信息,我可以通过以下操作返回两个操作...

df = pd.DataFrame({'year': ['1 (1991)', '10 (1991-2001)', '8 (1991-1998)', '2 (2000-2002)']})

           year
       1 (1991)
 10 (1991-2001)
  8 (1991-1998)
  2 (2000-2002)

df['year'] = df['year'].str.extract(r'\((.*)\)')

      year
      1991
 1991-2001
 1991-1998
 2000-2002

但是,理想情况下,有时候我只想提交一个动作,

例如

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)))
          ))
    ));

因此,如果我得到数据,我只想提交 ... mergeMap(data => [ if (data.currentDay !== undefined) // <-- how to do this currentDayActions.getCurrentDaySuccess(data.currentDay), myDataActions.getDataSuccess(data.data) ]),

当然,以上是不正确的语法,但我不太明白如何在此处获取此“ if”。

任何帮助都将不胜感激。

[UPDATE1]

与此类似的例子是here

尝试做同一件事的效果是在currentDayActions.getCurrentDaySuccess

1 个答案:

答案 0 :(得分:1)

if else语句可以解决问题:

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)))
          )
        )
      )
    )
  );