我有一个场景,当服务失败时,我必须传递请求有效负载,以便我可以返回错误响应。我的代码如下所示。
@Effect() doGetEvents$: Observable<Action> = this.actions$
.ofType(EVENTS)
.switchMap((action) => {
let eventDate = action.payload.date;
return this.http.service(action.payload);
})
.map(res => {
// success
if (res.status) {
return CustomActions.prototype.eventsResponse({ type: EVENTS_RESPONSE, payload: res.payload });
}
//failure
return CustomActions.prototype.EventsErrorResponse({
type: CustomActions.EVENTS_ERROR_RESPONSE,
payload: {
status: res.status,
errorMessage: res.errorMessage,
billDate: '10/01/2016', // <--- I need the eventDate got from the above switchMap
errorType: CustomActions.EVENTS + '_ERROR'
}
});
});
我尝试像这样传递
.switchMap((action) => {
let eventDate = action.payload.date;
return [eventDate, this.http.service(action.payload)];
})
但这不会执行 http
调用,也不会返回 .map()
参数上的响应。
还有一些选项可以使 eventDate
超出效果范围并在服务失败时分配它,但这不是一个更干净的方法,应该有某种方式传递数据,不确定我错过了什么!
最佳答案
如果您想要包含有效负载中的信息以及 HTTP 服务的结果,您可以使用 map
运算符,如下所示:
.switchMap((action) => {
return this.http
.service(action.payload)
.map(result => [action.payload.date, result]);
})
.map(([date, result]) => { ... })
关于javascript - ngrx/effect 将数据传递给运算符(operator),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41789835/