After searching extensively on SO for answers regarding item conversions in Javascript/Angular, I couldn't find a solution that addresses my specific problem. When retrieving data from Firestore as an object with potential duplicates, I need to perform a 1 to many conversion. The object extracted from Firestore is called 'MultipleCard', which includes a property called 'copies' indicating how many 'Cards' should be created.
postsCol: AngularFirestoreCollection<MultipleCard>;
posts: Observable<MultipleCard[]>;
cardsListObservable: Observable<Card[]>; //Undecided
cardsList: Card[]; //Undecided
constructor(private messageService: MessageService,
private db: AngularFirestore) {
this.messageService.add('Fetching cards');
this.postsCol = this.db.collection('cards');
this.posts = this.postsCol.valueChanges();
//?? Struggling to achieve the desired outcome here. Most operations result in a 1 to 1 conversion or affect the array directly.
}
Component
<mat-list *ngFor="let card of cardsList | async"> //Either cardsList or cardsListObservable
<mat-list-item>{{card.name}}</mat-list-item>
</mat-list>
How can I convert Observable into Observable or Card[]? For example, consider an array containing the following 'MultipleCard's:
[{ id: 1,
copies: 3},
{id: 2, copies:1}]
This array should be transformed into an array of 4 'Card' objects:
[{ id: 1, copyVersion:1},
{ id: 1, copyVersion:2}.
{ id: 1, copyVersion:3},
{ id: 2, copyVersion:1}]
I would appreciate any suggestions!
Edit 1
Attempted the following:
this.posts.subscribe((posts) => {
posts.forEach( post => {
console.log(post);
this.cardsList.push(post);
});
});
Resulted in:
core.js:1350 ERROR TypeError: Cannot read property 'push' of undefined at eval (deck-list.component.ts:40)
Final Updated Code:
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);
});
});
});