从数据库中获取值后,我试图将其放在变量中,但是当我这样做时,它给了我错误:

core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefinedTypeError: Cannot set property 'userNm' of undefined

这是我的ts代码:

userNm: string ='';

ngOnInit(){

   console.log("trying...");
   firebase.firestore().collection(`Students`)
   .where("authId", "==", this.userId)
   .get()
   .then(querySnapshot => {
     querySnapshot.forEach(function(doc) {
         console.log(doc.data().Name); // OK RESULT IN CONSOLE.LOG,NAME IS String in db.
         this.userNm=doc.data().Name;  // ERROR HERE
         console.log(this.userNm)
         console.log(doc.id, " ===> ", doc.data());
     });
   });


控制台和数据库的屏幕快照:

javascript - 无法设置userNm的属性未定义-LMLPHP

javascript - 无法设置userNm的属性未定义-LMLPHP

最佳答案

Javascript this中的function()关键字是指函数的范围。要使用成员变量,请使用箭头函数构造。您可以尝试以下

firebase.firestore().collection(`Students`)
  .where("authId", "==", this.userId)
  .get()
  .then(querySnapshot => {
    querySnapshot.forEach((doc) => {   // <-- Use arrow function here
      console.log(doc.data().Name);
      this.userNm = doc.data().Name;
      console.log(this.userNm)
      console.log(doc.id, " ===> ", doc.data());
    });
  });

10-04 15:22