Angular 6 и AngularFirestore ВСТАВИТЬ, ОБНОВИТЬ - PullRequest
0 голосов
/ 13 декабря 2018

В приведенном ниже коде у меня есть обработчик события кнопки, который при вызове получает questionId и userId.Затем он проверяет коллекцию ответов, чтобы узнать, ответил ли этот пользователь на данный вопрос.Если так, сделайте обновление, если нет, сделайте вставку.Этот код работает, почти.Это вызывает бесконечный цикл, когда я обновляюсь ?!Я не уверен, почему?Мысли?

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);
              });
        }

    }
);

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...