How to retrieve information of a loan (loan document fields) and the items within the specific loan (items collection of loan document) from firebase?

Issue

I am trying to get the information of a specific loan by it’s ID and the details of items in that loan to display it in the detail page. However, I am unable to and I do not know how to retrieve the loan and loan items using the loan service’s getLoanById method given to me.

detail.page.ts

export class DetailPage {
  loan: Loan;
  loanId: string;

  constructor(private route: ActivatedRoute, private loanService: LoanService) {
    this.loanId  this.route.snapshot.params.id;
    this.loan  this.loanService.getLoanById(this.loanId);
  }
}

loan.service.ts

  getLoanById(id: string) {
    return firebase.firestore().collection('loans').doc(id).get().then(doc > {
      let loan  new Loan(doc.data().username, doc.data().status, doc.data().duedate.toDate(), doc.id);

      return firebase.firestore().collection('loans/' + id + '/items').get().then(collection > {
        loan.items  []; // Empty array
        collection.forEach(doc > {
          let item  new Item(doc.id, doc.data().quantity);
          loan.items.push(item);
        })
        return loan;
      });
    });
  }

Solution

Change the getLoanById() to the following method:

 async getLoanById(id: string) : Promise<any> {
    const doc  await firebase.firestore().collection('loans').doc(id).get();
    let loan  new Loan(doc.data().username, doc.data().status, doc.data().duedate.toDate(), doc.id);
    const collection  await firebase.firestore().collection('loans/' + id + '/items').get();
    loan.items  []; // Empty array
    collection.forEach(doc_1 > {
      let item  new Item(doc_1.id, doc_1.data().quantity);
      loan.items.push(item);
    });
    return loan;
  }

Since the get() method is asynchronous, therefore use async/await to wait until the data is retrieved to then add it to the list. Then inside the DetailPage you can do the following:

   constructor(private route: ActivatedRoute, private loanService: LoanService) {
    this.loanId  this.route.snapshot.params.id;
    this.loanService.getLoanById(this.loanId).then((result){
      console.log(result);
     });
  }

The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise. Once a Promise is fulfilled or rejected, the respective handler function (onFulfilled or onRejected) will be called asynchronously.

Check:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Answered By – Peter Haddad

Leave a Comment