Angular NGRX @Effect捕获所有动作

时间:2019-07-29 18:07:41

标签: angular ngrx ngrx-effects

我有一个棱角分明的应用程序,在这里我希望产生副作用,以便将服务调用到第三方分析平台。我的想法是要做

 Any action fires -> Side effect catches everything -> Service to call analytics

话虽如此,我显然不想在每种效果中添加该流程。我只希望树的顶部有一个“包罗万象”的副作用,以捕获所有Ngrx动作,而不是分派动作,而是简单地调用服务。我在语法上遇到了麻烦...

@Injectable()
export class AmplitudeEffects {
  constructor(private actions$: Actions) {}

  @Effect()
  private *any action here* = this.actions$.pipe( <--what to put here
    ofType(), <-- leave empty to catch everything?
    mergeMap(() =>
      this.amplitudeService.sendValues(arg1, arg2, arg3, arg4).pipe(
        // catchError(error => of(new AmplitudeFailure(error)))
      )
    )
  );
}

2 个答案:

答案 0 :(得分:1)

这是一个效果的好用例,我也在Start using ngrx/effects for this中给出了此示例。

要回答您的问题,只需将ofType排除在外:

  @Effect()
  log = this.actions$.pipe(
    mergeMap(() =>
      this.amplitudeService.sendValues(arg1, arg2, arg3, arg4).pipe(
        // catchError(error => of(new AmplitudeFailure(error)))
      )
    )
  );

我不确定您是否要捕获该错误,因为这只是出于记录目的,因此您可以:

  @Effect({ dispatch: false })
  log = this.actions$.pipe(
    mergeMap(() =>
      this.amplitudeService.sendValues(arg1, arg2, arg3, arg4)
    )
  );

答案 1 :(得分:1)

只需删除ofType,您的错误处理就会终止可观察的对象,因此ngrx将停止工作,因此我添加了正确的方法来处理catchError。我应该看起来像这样,但是由于我不知道什么sendValues,所以我认为它将返回一个可观察的结果。

  @Effect()
  name = this.actions$.pipe(
      this.amplitudeService.sendValues(arg1, arg2, arg3, arg4).pipe(
          map((x: any)=> x),
          catchError((error: any, effect: Observable<Action>) => {
            return effect.pipe(startWith(new new AmplitudeFailure(error)));
          }
      )
    )
  );
相关问题