【发布时间】:2018-07-08 16:05:28
【问题描述】:
所以我已经阅读了许多关于 Javascript/Angular 中的项目转换的 SO 问题,但没有找到任何可以解决我的问题的内容。我从 Firestore 中提取一个可以有副本的对象。然后我需要使用 1 到多个转换来转换对象。来自 Firestore 的对象是“MultipleCard”。这个“MultipleCard”有一个名为“copies”的属性,用于表示应该创建多少“Cards”。
postsCol: AngularFirestoreCollection<MultipleCard>;
posts: Observable<MultipleCard[]>;
cardsListObservable: Observable<Card[]>; //Not sure which to use
cardsList: Card[]; //Not sure which to use
constructor(private messageService: MessageService,
private db: AngularFirestore) {
this.messageService.add('Fetching cards');
this.postsCol = this.db.collection('cards');
this.posts = this.postsCol.valueChanges();
//?? Nothing I do here seems to work correctly. Most operations act on the array itself or do a 1 to 1 conversion
}
组件
<mat-list *ngFor="let card of cardsList | async"> //Or cardsListObservable
<mat-list-item>{{card.name}}</mat-list-item>
</mat-list>
如何将 Observable 转换为 Observable 或 Card[]?例如,我可能有一个包含以下“MultipleCard”的数组
[{ id: 1,
copies: 3},
{id: 2, copies:1}]
这应该被转换成一个由 4 个“卡片”对象组成的数组:
[{ id: 1, copyVersion:1},
{ id: 1, copyVersion:2}.
{ id: 1, copyVersion:3},
{ id: 2, copyVersion:1}]
感谢任何见解!
编辑 1
尝试了以下方法:
this.posts.subscribe((posts) => {
posts.forEach( post => {
console.log(post);
this.cardsList.push(post);
});
});
但是得到:
core.js:1350 错误类型错误:无法读取未定义的属性“推送” 在 eval (deck-list.component.ts:40)
最终更新代码:
static fromMultiple(multipleCard: MultipleCard): Card[] {
const data: Card[] = [];
for (let i = 0; i < multipleCard.copies; i++) {
data.push(new Card(multipleCard));
}
return data;
}
this.postsCol = this.db.collection('cards');
this.posts = this.postsCol.valueChanges();
this.posts.subscribe((posts) => {
posts.forEach( post => {
const temp = Card.fromMultiple(post);
temp.forEach(tempCard => {
this.cardsList.push(tempCard);
});
});
});
【问题讨论】:
-
实际的问题/问题是什么?
-
@Zze 更新了问题的简化版本
-
显示您的服务代码?
-
@Haris 你指的是什么服务代码?我正在使用 AngularFirestore 数据库将对象拉到我上面发布的类中。
-
您可以使用
map将您的可观察对象转换为发出一个数组,而不是任何火力基地返回。即this.posts = this.postsCol.valueChanges().map(x => /*do stuff here*/)。此外,您应该使用带有 observable 的异步管道,即posts({{ posts | async }})。在你的地图函数中放置一个断点 - 调试是你的朋友。
标签: angular typescript rxjs google-cloud-firestore