首页 > 解决方案 > Angular - 从 Firebase 填充表单导致重复

问题描述

我正在根据查询填充表单。在这种情况下,应该有两个条目,但我得到一个重复:

  get childrenForm() {
    return this.recordForm.get('children') as FormArray;
  }

     // Get all students associated with the current record.
    const query = this.afs.collection('students', ref => ref.where('recordId', '==', this.currentRecordId));
    this.subscriptions.push(
       query.valueChanges()
       .subscribe(students => {
        console.log(`MD: RecordFormPage -> populateForm -> students`, students);
        students.forEach((child: any) => {
          const timestamp = child.dob.seconds;
          const date = new Date(timestamp * 1000);
          const childData = this.fb.group({
            fname: child.fname,
            lname: child.lname,
            dob: date,
            grade: child.grade,
            gender: child.gender,
            race: child.race,
            id: child.id
          });
          this.childrenForm.push(childData);
        });
      })
    );

注意重复的 Delvin Carrington 条目: 在此处输入图像描述

您会注意到在控制台中valueChanges()发出数据库中的第一个条目,然后发出第一个条目 + 第二个条目,从而产生三个结果: 在此处输入图像描述

所以我相信,如果有一种适当的方法可以等到valueChanges()所有数据都有,那么只有在那个时候,发出和/或推送数据this.chidrenForm——这应该可以解决它。知道订阅valueChanges()不会触发它的onComplete方法。先感谢您。

标签: angularrxjsgoogle-cloud-firestore

解决方案


您可以在每次运行时清除表单:

this.childrenForm.clear();

在你的 forEach 之前


推荐阅读