javascript - ngrx/effect 将数据传递给运算符(operator)

标签 javascript angular ngrx

我有一个场景,当服务失败时,我必须传递请求有效负载,以便我可以返回错误响应。我的代码如下所示。

@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/

相关文章:

javascript - 为什么 Facebook Javascript SDK 是异步加载的?

angular - 在网络应用程序中处理离线数据

angular - 特征切片为空时的 NgRx 选择器

node.js - 从 Angular 11 升级到 12 导致对等依赖冲突

angular - NGRX 8 将元素添加到存储中的数组

javascript - 如何根据其父 div 是否具有图像来确定 <p> 的高度

javascript - Div 滑动底部

javascript - 如何更新 meteor 中的电子邮件地址?

angular - 如何在 Angular4 中获取 FormControl 的值

angular - 我如何在 Angular 8 应用程序中支持 Internet Explorer?