如何将firestore数据字段分配给变量?

时间:2018-01-21 09:09:06

标签: angular typescript google-cloud-firestore

我有一个firebase集合'消息',我将文档添加到其中:

this.afs.collection('messages').add({ 'qn': message, 'student': this.student, 'upvotes': this.upvote });

upvotes字段由upvote或downvote按钮设置。当点击其中任何一个时,我称之为:

increment(messageId) { //decrement(messageId) for the downvote button
this.upvote += 1; //-=1 for the downvote button   
this.messageDoc = this.afs.doc('messages/' + messageId);
this.message = this.messageDoc.valueChanges();
this.afs.doc('messages/' + messageId).update({
  upvotes: this.upvote
});
}

问题是,我将upvotes变量定义为:private upvote: number = 0;

这意味着如果我重新加载页面并单击upvote或downvote,则该值将再次从0开始增加或减少,因为变量upvote未分配实际数据库值。我想通过将文档的upvotes字段中的数据分配到upvote变量来解决这个问题 - 我该怎么做?

编辑:管理以使其可以使用此

increment(messageId) {
this.upvote += 1;
let self = this;
let messageDoc = firebase.firestore().collection('messages').doc(messageId);

return firebase.firestore().runTransaction(function (transaction) {
  return transaction.get(messageDoc).then(function (sfDoc) {
    let upVote = sfDoc.data().upvotes + self.upvote;
    transaction.update(messageDoc, { upvotes: upVote });
    self.upvote = 0;
  });
}).then(function() {
  console.log("Transaction successfully committed!");
}).catch(function(err) {
  console.log("Transaction failed: " + err);
});
}

1 个答案:

答案 0 :(得分:0)

您可以Transactions使用

let self = this;
let messageDoc = firebase.firestore().collection('messages').doc(messageId);

return firebase.firestore().runTransaction((transaction) => {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(messageDoc).then((sfDoc) => {
        let upVote = sfDoc.data().upvotes + self.upvote;
        transaction.update(messageDoc, { upvotes: upVote });
    });
  }).then(() => {
      console.log("Transaction successfully committed!");
  }).catch((err) => {
      console.log("Transaction failed: ", err);
  });

并且不要忘记导入import * as firebase from 'firebase';