我当前的效果代码如下所示,这是我的效果代码,当前我正在其中从效果中调度单个动作。但是我想再派一个动作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.
那么如何实现呢?
答案 0 :(得分:4)
您可以使用switchMap
代替map
运算符,以便能够返回array
个动作,然后该动作将发出每个动作:
...
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);
])
)
);
));
为此,您需要在HttpClient
方法内以sendReservationRequest
返回“经典”响应:
sendReservationRequest(request: ReservationRequest) {
return this.httpClient.post(SERVICE_URL);
// no {observe: 'response'} here
}
注意:在此示例中非常简单,但是在某些情况下,可能需要测试errorResponse
中的catchError
内容。为了避免errorResponse.error.message
的任何问题...在此不讨论主题。
答案 1 :(得分:0)
我用另一种效果解决了此类问题,其中我过滤了成功操作:
from django.shortcuts import render
from django.core.mail import send_mail, EmailMultiAlternatives
# from .models import Contact_formular
def contactFormular(request):
return render(request, 'contact.html',{})
if request.method == 'POST':
name = request.POST['conName']
email = request.POST['conEmail']
message = request.POST['conText']
send_mail('New request', name, message, email , ['name@gmail.com'], fail_silently=False)
因此结构清晰,代码也不太复杂。