問題描述
切換地圖後在NGRX特效點擊功能中獲取動作道具 (Get action props in the NGRX effects tap function after switch Map)
我在 Angular 中有一個效果很好,但我希望在調用 switch 映射中的 API 後傳遞 action prop 變量。
這是效果
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}>()
);
我想得到我在開關地圖中傳遞的道具。我需要我傳遞的標誌值,以便我可以根據點擊運算符中的標誌做一些其他事情。這可能嗎?
參考解法
方法 1:
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.
(by Learn AspNet、mat.hudak)