无法读取 collection.set() 上未定义的 属性afs (Angularfirestore)

Cannot read propery afs (Angularfirestore) of undefined on collection.set()

我使用以下代码迭代数据集合,并在电子邮件匹配时更改字段。请注意,代码在集合上崩溃。迭代工作得很好。 afs 被初始化为 AngularFirestore

onChangeRole(email) {
  this.afs.collection("users").get().toPromise().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
      // doc.data() is never undefined for query doc snapshots
      console.log(doc.id, " => ", doc.data());

      if (doc.data().email == email) {
        this.afs.collection("users").doc(doc.id).set({
          role: 2
        })
      }
    });
  });
}

但我收到了:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'afs' of undefined TypeError: Cannot read property 'afs' of undefined

其中 afs 是 AngularFirestore

import { AngularFirestore, AngularFirestoreCollection , AngularFirestoreDocument} from '@angular/fire/firestore';

您必须在构造函数中初始化它,然后您就可以像您尝试的那样将它与 this.afs 一起使用。

例如:

constructor(private afs: AngularFirestore) { }

编辑: 更改箭头函数用法的函数词:

this.afs.collection("users").get().toPromise().then( querySnapshot => {
      querySnapshot.forEach( doc => {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());

        if (doc.data().email == email) {
          this.afs.collection("users").doc(doc.id).set({
            role: 2
          })
        }
      });
    });

这应该有效

onChangeRole(email) {
  const usersColl = this.afs.collection("users");
  usersColl.get().toPromise().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
      console.log(doc.id, " => ", doc.data());
      if (doc.data().email == email) {
        usersColl.doc(doc.id).set(
          { role: 2 },
          { merge: true }
        )
      }
    });
  });
}