在下面的代码中,我拥有的是按钮事件处理程序,该事件处理程序在调用时会获得一个QuestionId和一个UserId。然后,它检查Answers集合以查看该用户是否已经回答了给定的问题。如果是这样,请进行更新,否则请进行插入。该代码几乎可以正常工作。当我更新时,它会导致无限循环!我不确定为什么吗?有想法吗?
addAnswer(answer: string) {
var questionId = this.selectedQuestion.id;
var userId = this.selectedUser.id;
//FIRST: check to see if this user already answered this question
// if so, do an update, not an add
var answersRef = this.db.collection('Answers', ref => {
// Compose a query using multiple .where() methods
return ref
.where('userId', '==', userId)
.where('questionId', '==', questionId)
});
answersRef.snapshotChanges().subscribe(
data => {
console.log(data);
//
if (data.length > 0) {
//UPDATE as they already have an answer to the question
console.log('UPDATE');
data.map( a => {
console.log(a.payload.doc.id);
//
this.db.collection('Answers').doc(a.payload.doc.id).update({
answer: answer,
date: null,
isPublic: true,
//questionId: questionId,
//userId: userId,
})
.then( docRef => {
console.log("Document successfully updated!");
})
.catch( error => {
console.error("Error adding document: ", error);
});
});
}
else {
//INSERT
console.log('INSERT');
this.db.collection('Answers').add({
answer: answer,
date: null,
isPublic: true,
questionId: questionId,
userId: userId,
})
.then( docRef => {
console.log("Document written with ID: ", docRef.id);
})
.catch( error => {
console.error("Error adding document: ", error);
});
}
}
);
}