ANGULAR 如何推送到可观察数组?英雄:Observable<Hero[]>
ANGULAR How to push to observable array? hero: Observable<Hero[]>
给定一个数组:
// hero.service.ts
hero: Observable<Hero[]>;
你会怎么做类似的事情:hero.push(newHero)?
不确定您要实现的目标,但因为您标记了 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.
给定一个数组:
// hero.service.ts
hero: Observable<Hero[]>;
你会怎么做类似的事情:hero.push(newHero)?
不确定您要实现的目标,但因为您标记了 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.