0
votes

I'm new to ngrx and Angular development. I have a collection of trades in my store. An effect listens to LoadTradeRequest which fires an http request to get Observable and triggers a LoadTradeSuccess or LoadTradeFailure.

@Effect()
loadTrade$: Observable<Action> = this.actions$.pipe(
ofType(ActionTypes.LoadTradeRequest),
mergeMap((action: actions.LoadTradeRequest) =>
  this.remoteApiService.loadTrade(action.payload).pipe(
    map(trade => new actions.LoadTradeSuccess(trade)),
    catchError(err => of(new actions.LoadTradeFailure(err)))
  )
 )
);

A reducer function for LoadTradeSuccess action adds the loaded Trade to the store.

  case ActionTypes.LoadTradeSuccess: {
  return { ...state, trades: [...state.trades, action.payload] };
}

My State declaration is

trades: Trade[];

All works fine so far. I now need to change the State to a make the trades collection keyed on a unique identifier which is given in the action payload of LoadTradeRequestAction

Desired State

trades: DictionaryItem<string, Trade>[];

where DictionaryItem is

export interface DictionaryItem<K, V> { 0: K; 1: V; }

How do I pass in a property of the action which triggered the effect to the action which it triggers along with the http response. The block below doesn't work and just tries to illustrate what I want to achieve.

@Effect()
loadTrade$: Observable<Action> = this.actions$.pipe(
ofType(ActionTypes.LoadTradeRequest),
mergeMap((action: actions.LoadTradeRequest) =>
this.remoteApiService.loadTrade(action.payload).pipe(
map(trade => new actions.LoadTradeSuccess({**action.payload.UniqueIdentifier**, trade})),
catchError(err => of(new actions.LoadTradeFailure(err)))
 )
)
1
Hi Rahul, Can you please attach the error you are getting?Udi Mazor
@rahul you’re trying to pass 2 parameters to action constructor. Type the payload as object with 2 properties and pass matching object. Also any reason not to use the latest version of ngrx? (just follow the docs)Andrew Allen
I am not quite sure what you want, but you do have visibility over action in the "what you want to achieve example", so you could retrieve the key from it.cabesuon

1 Answers

1
votes

The constructor of you action must receive two params:

class LoadTradeSuccess {
  constructor(readonly id: any, readonly  trade: any){}
}

Or a payload object, but then you have to create the object in the effect

class LoadTradeSuccess {
  constructor(readonly payload: any){}
}


map(trade => new actions.LoadTradeSuccess({id: action.payload.UniqueIdentifier, trade: trade })),