【问题标题】:Subscribe emits one item at the time instead of a list in Rxjs订阅一次发出一个项目,而不是 Rxjs 中的列表
【发布时间】:2017-12-03 09:43:47
【问题描述】:

我目前正在努力找出 Angular 4 应用程序中 Rxjs 的行为。

我的代码是:

this.server.get("incidents") //http get resource
.flatMap((res) => res.value) //the incident array is in a property called value of the json returned
.map((incident) => new Incident(incident)) // conversion from json to typed class
.subscribe(i => {this.ng2TableData.push(i);}) //subscribe

在最后一行,我希望 subscribe 方法立即为我提供整个列表,相反,似乎可观察对象当时返回一个 Incident 并且 subscribe 函数被调用 N 次,因此迫使我拥有push 方法,而不是一次性构建 ng2TableData

如何订阅整个列表,而不是一次订阅一项?

【问题讨论】:

  • 那么不要使用flatMap,因为flatMap会将您的数组值扁平化为可观察的值流。
  • 你为什么首先使用 flatMap?
  • 但如果我使用地图而不是平面地图,在第二张地图中,我将获得完整数组而不是单个事件作为输入。使用地图而不是平面地图的正确方法是什么?

标签: angular rxjs observable


【解决方案1】:

flatMap 会将您的数组扁平化为可观察的值流。您只想使用map。您可以再次使用map,将数组中的每个对象作为类的实例,如下所示:

this.server.get("incidents")
  .map(res => res.value.map(incident => new Incident(incident)))
  .subscribe(data => console.log(data)) // data is an array!

现在您将数组放入 subscribe 中。

【讨论】:

  • 感谢您的帮助,就是这样!一旦你写了它就很明显了,但在我看来,解决方案是串联 rxjs 方法,而不是嵌套的 map 方法
猜你喜欢
  • 1970-01-01
  • 2018-09-05
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 2020-01-06
  • 1970-01-01
相关资源
最近更新 更多