【问题标题】:ngrx Effects: Dispatch Empty Actionngrx 效果:调度空动作
【发布时间】:2018-11-22 19:55:38
【问题描述】:

如何让我的 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 },但实际效果大约有五个结果,其中只有一个不使用动作,所以我宁愿最后一个也返回一些东西。

【问题讨论】:

  • fire.some.effect 是什么?是this.store$.dispatch吗?
  • @martin - 不,这是一个重新路由:this.router.navigate(['url']); @cartant - 感谢您的链接,但我已经找到了您的答案,我认为它不适用于 ng 6。至少没有一个你提到的选项对我没有用。

标签: angular rxjs ngrx


【解决方案1】:

你可以使用过滤器

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

如果你还需要其他情况,你可以用dispatch: false写另一个效果

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我建议更进一步,创建两个效果,一个使用{ dispatch: false } 将具有x !== y 过滤器,另一个使用x === y 过滤器。
    【解决方案3】:

    这对我有用(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;
        })
      );
    

    【讨论】:

    • 您能否介绍一下 EMPTY 是什么,或者它来自什么包?
    • 不要使用EMPTY,因为它完成了流并且没有进一步的事件被监听!
    • Mateo Tibaquira,对不起,我不同意。为什么 ?请问可以给点参考吗? HttpClient.get 也是一个完成的可观察对象。请参阅 [ngrx.io/guide/effects#writing-effects](Official docs) 提到它来管理 catchError。谢谢。
    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 2020-01-10
    • 2023-03-18
    • 2022-11-16
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多