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

问题描述 投票:0回答:2

我使用以下代码迭代数据集合,并在电子邮件匹配时更改字段。请注意,代码在集合上崩溃。迭代工作正常。 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
        })
      }
    });
  });
}

但我收到:

错误:未捕获(在承诺中):TypeError:无法读取未定义的属性'afs'TypeError:无法读取未定义的属性'afs'

其中afs是AngularFirestore

import { AngularFirestore, AngularFirestoreCollection , AngularFirestoreDocument} from '@angular/fire/firestore';
angular typescript angularfire
2个回答
0
投票

这应该工作

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

1
投票

你必须在构造函数中初始化它,然后你将能够像你想要的那样使用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
          })
        }
      });
    });
© www.soinside.com 2019 - 2024. All rights reserved.