首页 > 解决方案 > 在里面设置函数参数然后用firestore块

问题描述

所以我试图在处理firestore时在then块内设置一个对象参数,但由于某种原因它没有被设置。我的语法有问题吗?我认为 using=>可以让我做到这一点。

updateLedger(id: string, data: any) {
    this.afs.collection('chartofaccounts').doc(id).ref.get().then(doc => {
      if (doc.data().normalside === 'debit') {
        ///// set the runningBalance of the data object passed into the function here
        data.runningBalance = doc.data().debitAmount - doc.data().creditAmount;
      } else {
        ///// or here...
        data.runningBalance = doc.data().creditAmount - doc.data().debitAmount;
      }
    });
    return this.afs.collection('ledger').add(data);
  }

标签: javascriptgoogle-cloud-firestore

解决方案


这是一种可能的方法,但我不确定你是否真的需要回调,重要的想法只是在 promise 解析时添加this.afs.collection('ledger').add(data);这一行(异步)。.then我还为您提供了回调以检查是否有帮助。

updateLedger(id: string, data: any, callback: function) {
  this.afs.collection('chartofaccounts').doc(id).ref.get().then(doc => {
    if (doc.data().normalside === 'debit') {
      ///// set the runningBalance of the data object passed into the function here
      data.runningBalance = doc.data().debitAmount - doc.data().creditAmount;

      // You set it here maybe you don't even need the callback
      this.afs.collection('ledger').add(data);
      callback(data);
    } else {
      ///// or here...
      data.runningBalance = doc.data().creditAmount - doc.data().debitAmount;

      // You set it here maybe you don't even need the callback
      this.afs.collection('ledger').add(data);
      callback(data);
    }
  });
}

// In the call you receive the result
updateLedger(id, data, (resultData) => {
  console.log(resultData)
})

确保then如果没有被调用,添加一个.catch语句,也许还有其他一些问题......


推荐阅读