Angular 2:合并一个可观察的"内部"另一个

时间:2018-02-11 13:12:31

标签: angular observable subscribe

在页面加载时,我将此数据作为项目加载到模板中:

{
    "id": "1",
    "name": "Leonardo",
    "weapon": "sword",
},
{
    "height": "2",
    "name": "Donatello",
    "weapon": "stick",
},

我在我的组件中使用它加载数据:

this.dataSubscription = this.dataService.getAllTurtles().subscribe(res => this.turtles = res);

每个项目还有一个按钮" LOAD MORE DATA"。当我点击它时,它会加载一些属于该特定项目的额外数据:

this.dataSubscription = this.dataService.getData(id).subscribe(res => this.singleData = res);

加载我

{
    "favoritePizza": "Hawai",
}

现在,我想将这些数据合并到原始数据流中,所以我有:

{
    "id": "1",
    "name": "Leonardo",
    "weapon": "sword",
    "favoritePizza": "Hawai"
},
{
    "id": "2",
    "name": "Donatello",
    "weapon": "stick",
}

但我不确定如何以这种方式连接数组。目前我用concat做的时候:

this.dataSubscription = this.dataService.getData(id).subscribe(res => this.turtles = this.turtles.concat(res));

我只是得到了连接的数组:

{
    "id": "1",
    "name": "Leonardo",
    "weapon": "sword",
},
{
    "id": "2",
    "name": "Donatello",
    "weapon": "stick",
}
{
    "favoritePizza": "Hawai"
}

如何使用它的ID访问数组中的特定项目并添加我稍后加载的数据?

3 个答案:

答案 0 :(得分:1)

this.dataService.getAdditionalData(id)
  .subscribe(data => {
    this.turtles = this.turtles.map(i => {
      if (i.id !== id) {
        return i;
      }
      return { ...i, ...data };
    })
  })

示例https://stackblitz.com/edit/angular-tl4mt1?file=app%2Fapp.component.ts

答案 1 :(得分:0)

你可以做这样的事情



var a1 = [{
  "id": "1",
  "name": "Leonardo",
  "weapon": "sword",
  "favoritePizza": "Hawai"
}, {
  "id": "2",
  "name": "Donatello",
  "weapon": "stick",
}]

var a2 = {
  "favoritePizza": "Hawai",
}

a1 = a1.map((e) => {
  return e.id === "1" ? Object.assign(e, a2) : e
})

console.log(a1);




虽然可能有更好的选择!!!

答案 2 :(得分:0)

也许您的通话是从按钮"加载更多数据"

完成的
this.dataSubscription = this.dataService.getData(id).subscribe(res => this.singleData = res);

应该命名为

this.dataSubscription = this.dataService.getTurtle(1).subscribe(res => this.singleData = res);

使用getTurtle将Observable返回给Object Turtle,它通过设计文件包含到mongoDB中,包含Turtle的详细信息,包括最喜欢的披萨:

{
  "id": "1",
  "name": "Leonardo",
  "weapon": "sword",
  "favoritePizza": "Hawai"
}