[英]How to assign firestore data field to a variable?
I have a firebase collection 'messages', and I add documents into it: 我有一个firebase集合“消息”,并向其中添加文档:
this.afs.collection('messages').add({ 'qn': message, 'student': this.student, 'upvotes': this.upvote });
The upvotes field is set by a upvote or downvote button. upvotes字段由upvote或downvote按钮设置。 When either of them are clicked, I call this method:
当它们中的任何一个被单击时,我将调用此方法:
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
});
}
The problem with this is, I defined the upvotes variable as: private upvote: number = 0;
问题是,我将upvotes变量定义为:
private upvote: number = 0;
This means that if I reload the page and click upvote or downvote, the value will just increase or decrease starting from 0 again, as the variable upvote is not assigned the actual database value. 这意味着如果我重新加载页面并单击upvote或downvote,则该值将再次从0开始增加或减小,因为没有为变量upvote分配实际的数据库值。 I want to fix this by assigning the data in the upvotes field of the document into the upvote variable - how can I do this?
我想通过将文档的upvotes字段中的数据分配到upvote变量来解决此问题-我该怎么做?
Edit: Managed to make it work using this 编辑:设法使它使用此
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);
});
}
You can use Transactions
for that 您可以使用
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);
});
and don't forget to import import * as firebase from 'firebase';
并且不要忘记
import * as firebase from 'firebase';
导入import * as firebase from 'firebase';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.