gpt4 book ai didi

angular - 如何从 NgRx 中的单个效果分派(dispatch)多个 Action ?

转载 作者:行者123 更新时间:2023-12-04 12:39:24 26 4
gpt4 key购买 nike

我当前的效果代码是这样的,这是我的效果代码,目前我正在从效果中调度单个 Action 。但是我想发送一个我在下面的效果代码中评论过的 Action notificationNew()。

    bookPropertyRequest$ = createEffect(() => {
return this.actions$.pipe(
ofType(ReservationReqActions.bookPropertyRequest),
concatMap(action =>
this.ReservationReqService.sendReservationRequest(action.reservationRequest).pipe(
map(response => {
if (response.status) {
this.helperService.snackbar('Request Sent.');
// Here i want to dispatch another action - notificationNew()
return ReservationReqActions.bookPropertyRequestSuccess({ reservationRequest: response.result });
} else {
const errorCode = response.errorCode;
if (errorCode !== null) {
this.helperService.errorAlert('', response.message, 'error');
return ReservationReqActions.bookPropertyRequestFailure({
error: {
type: response.errorCode || null,
message: response.message
}
});
}
}
}),
catchError(error => EMPTY)
)
)
);
});

Now I want to dispatch another action from action notificationNew() when the above-mentioned effect is success. So my my concern is how we can dispatch multiple actions from single effect.

那么如何实现呢?

最佳答案

您可以使用 switchMap 代替 map 运算符,以便能够返回一个 array Action ,然后它会发出每个 Action :

... 
this.ReservationReqService.sendReservationRequest(action.reservationRequest).pipe(
switchMap(response => {
if (response.status) {
this.helperService.snackbar('Request Sent.');
return [
ReservationReqActions.bookPropertyRequestSuccess({ reservationRequest: response.result }),
UiActions.notificationNew({...})
]
...

建议

这里有一个用更少的代码进行重构的提议:

bookPropertyRequest$ = createEffect(() => this.actions$.pipe(
ofType(ReservationReqActions.bookPropertyRequest),
concatMap(action =>
this.reservationReqService.sendReservationRequest(action.reservationRequest).pipe(
switchMap(response => [
ReservationReqActions.bookPropertyRequestSuccess({ reservationRequest: response.result }),
UiActions.notificationNew({...})
]),
catchError(errorResponse => [
ReservationReqActions.bookPropertyRequestFailure({
error: errorResponse.error
}),
UiActions.errorAlert(errorResponse.error.message);
])
)
);
));

为此,您需要在 sendReservationRequest 方法中使用 HttpClient 返回“经典”响应:

sendReservationRequest(request: ReservationRequest) {
return this.httpClient.post(SERVICE_URL);
// no {observe: 'response'} here
}

注意:在这个例子中非常简单,但在某些情况下可能需要测试 catchError 中的 errorResponse 内容。为避免 errorResponse.error.message 出现任何问题...此处不在主题之列。

关于angular - 如何从 NgRx 中的单个效果分派(dispatch)多个 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60943746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com