【问题标题】:ANGULAR How to push to observable array? hero: Observable<Hero[]>角度如何推送到可观察数组?英雄:Observable<英雄[]>
【发布时间】:2018-10-15 07:41:33
【问题描述】:

给定一个数组:

// hero.service.ts
hero: Observable<Hero[]>;

你会如何做类似的事情:hero.push(newHero)?

【问题讨论】:

标签: angular typescript firebase rxjs angularfire


【解决方案1】:

不确定您要达到的目标,但因为您标记了 firestore。我想您可以稍后使用 angularfirestorecollection 并将它们映射到可观察数组。

cardsCollection: AngularFirestoreCollection<Card>;
  cardDoc: AngularFirestoreDocument<Card>;
  cards: Observable<Card[]>;

在初始化时,您会将它们绑定在一起。

ngOnInit() {
  this.cards = this.cardsCollection.snapshotChanges().map(changes => {
    return changes.map(a => {
      const data = a.payload.doc.data() as Card;
      data.id = a.payload.doc.id;
      return data;
    });
  });
}

然后您可以将卡片添加到 AngularFirestoreCollection。

addCard(card: Card) {
    this.cardsCollection.add(card);
}

希望这会有所帮助。如果您想查看我的完整代码和项目,请转到我的github

【讨论】:

  • 太棒了!你的例子帮助我理解了一些让它对我有用的东西!谢谢! :)
  • 我很高兴!您应该编辑适合您的解决方案的问题。
猜你喜欢
  • 2019-10-09
  • 2017-11-21
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多