Search code examples
angularngrxngrx-effects

Get action props in the NGRX effects tap function after switch Map


I have an effect in Angular which is working fine but I am looking to get action prop variable to be passed on after the API in switch map is called.

Here is the effect

    updateCustomer$ = createEffect(() =>
    this.actions$.pipe(
        ofType(updateCustomer),
        switchMap(action =>
            this.customerService.updateCustomer(action.customer).pipe(
                map(response => {
                    return successLoad({ data: response });
                }),
                catchError(EMPTY)
            )
        ),
        tap((action) => {
            console.log(action); I want to get props that I passed in the switch map. I need the value of flag that I passed so I can do some other things based on the flag
            //Do something
        })
    )
    );

Action


export const updateCustomer = createAction(
    '[Component] Add Customer',
    props<{ customer: customer, flag:string}>()
);

I want to get props that I passed in the switch map. I need the value of flag that I passed so I can do some other things based on the flag in the tap operator. Is that possible?


Solution

  • It is possible, but workflow depends on what you want to do with it. Do you want to dispatch another action in the tap, or you just want to do some other stuff? If it's only for other stuff then map your action and updateCustomer response to the object and process it in the following map operator. That way your effect will still return the successLoad action and you have an access to

    updateCustomer$ = createEffect(() =>
      this.actions$.pipe(
      ofType(updateCustomer),
      switchMap(action =>
        this.customerService.updateCustomer(action.customer).pipe(
          map(response => ({ action, response })),
          catchError(EMPTY)
        )
      ),
      //filter(response => !!response) // might neeed to add a filter for EMPTY response, not sure if !! is enough
      map(({action, response}) => {
        console.log(action); // your first action is here for some magic
        return successLoad({ data: response }); // return new action with data from updateCustomer
      }),
      filter(action => !!action) // failsafe is `updateCustomer` fails
    );
    

    If you want to return multiple actions, then replace the last map with switchMap and return the array of actions.