Reputation: 669
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)))
)
)
Upvotes: 0
Views: 738
Reputation: 15505
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 })),
Upvotes: 1