There is an object called "loans" with a list of objects named "items" stored within it. While I can retrieve the attributes of "loan" using page.ts, I face difficulty in extracting the attributes of the "items" object inside the "loan" object when trying to access them through "loan.items".
Despite console.log showing that "items" and its attributes are present within the "loan" object, using "loan.items" returns an empty array. My intention is to iterate through each item in "loan.items" using a for loop.
Here is a screenshot displaying what console.log(loan) returns
Here is a screenshot illustrating what console.log(loan.items) returns
In loan.page.ts:
this.loanService.getAllCurrentOrPastLoans("username", user.email, "current")
.subscribe(data => {
this.currentLoans = data;
for (let loan of this.currentLoans) {
if (loan.status != "rejected") {
this.currentLoansNo += 1;
for (let item of loan.items) {
this.currentLoansItemNo += item.quantity;
}
}
}
});
In loan.service.ts:
getAllCurrentOrPastLoans(whereFilter: string, whereValue: any, currentOrPast: string): Observable<any> {
return new Observable(observer => {
firebase.firestore().collection('loans').where(whereFilter, '==', whereValue).orderBy('duedate').onSnapshot(collection => {
let array = [];
collection.forEach(doc => {
if (currentOrPast == 'current') {
if (doc.data().status != 'completed') {
// Add loan into array if there's no error
try {
let loan = new Loan(doc.data().username, doc.data().status, doc.data().duedate.toDate(), doc.id);
array.push(loan);
// Read subcollection '/loans/<autoID>/items'
let dbItems = firebase.firestore().collection('loans/' + doc.id + '/items');
dbItems.onSnapshot(itemsCollection => {
loan.items = []; // Empty array
itemsCollection.forEach(itemDoc => {
let item = new Item(itemDoc.id, itemDoc.data().quantity);
loan.items.push(item);
});
});
} catch (error) { }
}
} else if (currentOrPast == 'past') {
if (doc.data().status == 'completed') {
// Add loan into array if there's no error
try {
let loan = new Loan(doc.data().username, doc.data().status, doc.data().duedate.toDate(), doc.id, doc.data().returnstatus);
array.push(loan);
// Read subcollection '/loans/<autoID>/items'
let dbItems = firebase.firestore().collection('loans/' + doc.id + '/items');
dbItems.onSnapshot(itemsCollection => {
loan.items = []; // Empty array
itemsCollection.forEach(itemDoc => {
let item = new Item(itemDoc.id, itemDoc.data().quantity);
loan.items.push(item);
});
});
} catch (error) { }
}
}
});
observer.next(array);
});
});
}