Search code examples
angularngrxngrx-effects

Angular NGRX @Effect to catch all actions


I have an angular app where I want a side effect to call a service to a 3rd party analytics platform. My thought was to do

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

With that said, I obviously don't want to add that flow in every effect. I just want a "catch-all" side effect at the top of the tree to catch any and all Ngrx actions, and instead of dispatching an action, to simply call the service. I am having trouble with the syntax...

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

Solution

  • That's a good use case for an Effect, I also give this example in Start using ngrx/effects for this.

    To answer your question, you can just leave the ofType out of it:

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

    I'm not sure if you do want to catch the error, as this is just for logging purposes, so you could do:

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