Search code examples
angulartypescriptreduxngrx

NGRX actions with common parameter structure


In angular, I am trying to have a shared error handling mechanism for NgRX effects. I want to have a common interface that all error Actions will implement. For example:

export interface ErrorProperties { error: string };

const createFailed = createAction('[CreateFailed]', props<ErrorProperties>());
const deleteFailed = createAction('[DeleteFailed]', props<ErrorProperties>());

I want to be able to use all of them in a single Effect, like this:

const errorActions: ? = [createFailed, deleteFailed];

handleError = createEffect(() =>
  this._actions.pipe(
    ofType(...errorActions),
    tap((action) => console.log(action.error));
  )
);

I want the effect to have type safety and to recognize that action is guaranteed to have the error property, but I'm not sure what type should errorActions have.


Solution

  • In order for this to have a proper answer, I'll write again the solution below:

    export interface ErrorProperties { error: string };
    
    const createFailed = createAction('[CreateFailed]', props<ErrorProperties>());
    const deleteFailed = createAction('[DeleteFailed]', props<ErrorProperties>());
    

    And the effect:

    const errorActions = [createFailed, deleteFailed];
    
    handleError = createEffect(() =>
      this._actions$.pipe(
        ofType(...errorActions),
        tap(action => console.log(action.error))
      )
    )