gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:51:43 24 4
gpt4 key购买 nike

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

core.js:6014 ERROR 错误:未捕获( promise 中):TypeError:无法设置未定义的属性“userNm”
类型错误:无法设置未定义的属性“userNm”

这是我的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());
});
});

控制台和数据库截图:

enter image description here

enter image description here

最佳答案

Javascript function() 中的

this 关键字指的是函数的作用域。要使用成员变量,请使用箭头函数构造。您可以尝试以下方法

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

关于javascript - 无法将 userNm 的属性设置为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60910564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com