Typescript Help - Pass an action by reference in a different NGRX action props

Discussão em 'Angular' iniciado por Tom Ford, Janeiro 14, 2025.

  1. Tom Ford

    Tom Ford Guest

    I have a handful of models that are shared across multiple parent entities in my application. Things such as phone numbers, addresses, email addresses.

    In my shared address component, I want to pass the user specific "success" and "failure" actions to my effect which will emit these success and failure functions I have provided as props. These actions passed by reference will be handled by my user reducer and effects to update the store with the api response, show a notification.


    // my generic address update action
    export const dispatchUpdateAddress = createAction(
    "Change generic address object",
    props<{ payload: any, onSuccess: ActionCreator, onFailure: ActionCreator>()
    );

    // specific to the user parent entity of address
    export const dispatchUserAddressUpdateSuccess = createAction(
    "Do user specific thing on success",
    props<{ payload: any >()
    );

    // specific to the user parent entity of address
    export const dispatchUserAddressUpdateFailure = createAction(
    "Do user specific thing on failure",
    props<{ payload: any >()
    );


    export class AddressEffects {
    updateAddress$ = createEffect(() =>
    this.actions$.pipe(
    ofType(dispatchUpdateAddress),
    mergeMap((action) =>
    this.dataService.update$(action.data).pipe(
    map((res) => action.onSuccess(res.payload) as unknown as Action<string>),
    catchError((res) => of(action.onFailure(res) as unknown as Action<string>))
    )
    )
    )
    );
    }
    // implementation
    export class SharedAddressComponent {

    updateAddress(payload: {address1: string, address2: string}) {
    this.store.dispatch(dispatchUpdateAddress({
    payload,
    // to be handled in my user.effects
    onSuccess: dispatchUserAddressUpdateSuccess,
    onFailure: dispatchUserAddressUpdateFailure

    })
    }
    }


    This code works fine, but I really don't like that I am having to cast my effect result as Action<string>.

    What is the correct type for onSuccess and onFailure?

    Continue reading...

Compartilhe esta Página