ngrx效果:派遣空行动

时间:2018-06-13 09:29:15

标签: angular rxjs ngrx

如何让我的ngrx / store效果分派空动作?我正在运行Angular 6 / rxjs 6:

  @Effect()
  testEffect$ = this.actions$.ofType(FIRST_ACTION).pipe(
    map((x) => {
       if (x === y) {
          return new SECOND_ACTION;
       } else {
          fire.some.effect;
          return EMPTY;
       }
    })
  );

目前,我收到两个错误:Effect "testEffect$" dispatched an invalid action: [object Object]后跟TypeError: Actions must have a type property

我找到this answer,但它似乎不适用于ng / rxjs 6.到目前为止,我已经尝试了以下(无效):

EMPTYObservable.empty()Observable.of()Observable.of([]){ type: 'EMPTY_ACTION' }

任何帮助将不胜感激!我知道我可以使用{ dispatch: false },但实际效果大约有五个结果,其中只有一个没有使用动作,所以我宁愿让最后一个也返回一些东西。< / p>

3 个答案:

答案 0 :(得分:5)

这是一个可能的解决方案:

@Effect()
  testEffect$ = this.actions$.ofType(FIRST_ACTION).pipe(
    tap((x) => { // do some side effect here
        if (x !== y ) {
            fire.some.effect;
        }
    }),
    filter((x) => x === y), // proceed only if condition is true
    map((x) => {
       return new SECOND_ACTION; // then return the needed action
    })
  );

答案 1 :(得分:1)

您可以只使用过滤器

@Effect()
testEffect$ = this.actions$.ofType(FIRST_ACTION).pipe(
  filter(x => x === y),
  map( x => new SECOND_ACTION)
)

如果您仍然需要其他情况,可以使用dispatch: false

编写另一个效果

答案 2 :(得分:-1)

这对我有用(ng6):

@Effect()
boardOpened$ = this.actions$
  .ofType<BoardActions.Open>(BoardActions.OPEN)
  .pipe(
    withLatestFrom(this.store.select(BoardSelectors.getState)),
    map(([action, state]: [Action, BoardReducer.State]) => {
      return !BoardReducer.isLoaded(state)
        ? new BoardActions.Load()
        : EMPTY;
    })
  );

@Effect()
boardOpened$ = this.actions$
  .ofType<BoardActions.Open>(BoardActions.OPEN)
  .pipe(
    withLatestFrom(this.store.select(BoardSelectors.getState)),
    switchMap(([action, state]: [Action, BoardReducer.State]) => {
      return !BoardReducer.isLoaded(state)
        ? of(new BoardActions.Load())
        : EMPTY;
    })
  );