2
votes

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)))
      )
    )
  );
}
2
Just commenting out ofType() function should do the work. - Mazedul Islam

2 Answers

1
votes

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

Just remove the ofType and your error handling would just terminate the observable so ngrx would stop working so I added the right way to handle the catchError. I should look like that but since I dont know what sendValues does I figured that it would return an observable.

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