无法设置 userNm 的属性未定义

use*_*442 1 javascript typescript ionic-framework angular google-cloud-firestore

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

core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: 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());
     });
   });
Run Code Online (Sandbox Code Playgroud)

控制台和数据库截图:

在此处输入图片说明

在此处输入图片说明

Mic*_*l D 5

thisJavascript 中的关键字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());
    });
  });
Run Code Online (Sandbox Code Playgroud)