【问题标题】:How to use multiple flatMap responses in map operator in different functions?如何在不同功能的地图运算符中使用多个 flatMap 响应?
【发布时间】:2020-03-30 21:38:10
【问题描述】:

我一直在尝试找到一种方法,将来自前一个 flatMap 运算符的 map 函数中的多个操作链接起来。

当前功能:

flatMap(
  someResponse=> combineLatest([
    this.locator.function(someResponse, variable2),
    this.function1(someResponse),
  ])
),
map(([response1, response2]) => this.function3(response1, response2));

所需的新功能是这样的:

flatMap(someResponse =>
  combineLatest([
    this.locator.function(someResponse, variable2),
    this.function1(someResponse),
    this.locator.function2(someResponse, variable3)
  ])
),
map(([response1, response2, response3]) => {
  this.function3(response1, response2);
  this.function4(response3);
})

我尝试了另一张地图,但它得到了之前的地图响应,而不是 flatMap。我对这些运营商的工作方式并不完全有信心。比如switchMap、contactMap、mergeMap等。我没找到办法。

我在 flatMap 中链接并组合了 3 个函数,然后我想使用响应来执行一些其他操作。

我该怎么做?

【问题讨论】:

  • 所以你想运行一个 observable,然后并行链接 3 个 observable,然后在 3 个 observable 都返回值时调用一些同步函数?
  • 没错。或者如果有更好的方法而不是这种结构。
  • 在您的示例中,您想在map 中做什么?
  • 如果最后一次调用是同步的,那么订阅flatMap而不是使用map不是很优雅吗?
  • 它们都在映射来自后端的一些响应。所有函数都返回数组。

标签: angular typescript rxjs


【解决方案1】:

可能还有其他一些优雅的解决方案。但目前以下解决方案应该可行。

在第一种情况下,您将返回由this.function3(response1, response2) 返回的数组。因为没有大括号的箭头函数实际上转换为带有返回语句的函数。例如。 map((...) => function(...)) 类似于写map((...) => { return function(...)) }

所以在第二种情况下,创建一个对象并推送两个函数返回的数组。然后返回对象。

flatMap(someResponse =>
  combineLatest([
    this.locator.function(someResponse, variable2),
    this.function1(someResponse),
    this.locator.function2(someResponse, variable3)
  ])
),
map(([response1, response2, response3]) => {
  return {
    'result1': this.function3(response1, response2),
    'result2': this.function4(response3)
  }
})

那么当你订阅 observable 时,来自函数 1 和 2 的数组可以分别被 response.result1response.result2 访问。

【讨论】:

  • 嗨@Michael,感谢您的努力,但这也不起作用。类型 'Observable' 不可分配给类型 'Observable'。如果我添加另一个运算符,但在另一个链中使用 flatMap 响应而不是 map() 响应怎么办? (比如再添加一个 map() 但使用第三个函数答案?
猜你喜欢
  • 1970-01-01
  • 2021-04-14
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多