我有一个问题:当我想在数据库中创建假用户时,一切都像超级按钮一样工作,直到我开始“ for”循环。
这时,我出现了这个错误:
添加文档时出错:TypeError:无法读取以下内容的属性“ firestore” 未定义
我已经尝试了多种方法,但是没有用……您有个主意吗?
谢谢大家!
create_NewUser(data:any){
this.firestore.collection('Users-test').add({
name:data.name,
town:data.town,
gender:data.gender,
email:data.email,
picture:data.picture,
birthdate:data.birthdate
})
.then(function(docRef) {
// console.log("Document written with ID: ", docRef.id);
let nbInterest:any = data.interests.length;
// let nbAvailaibilities:any = data.interests.length;
for (let index = 0; index < nbInterest; index++) {
this.firestore.collection('Users-test').doc("/" + docRef.id + "/interests/" + index).add({
interest:data.interests[index]
})
}
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
答案 0 :(得分:2)
取自here:
在经典函数表达式中,this关键字根据调用上下文而绑定到不同的值。但是,使用箭头功能时,这在词法上受约束。这意味着它使用包含箭头功能的代码中的this。
这意味着:在您作为参数传递给then
this
的函数中未定义。
您可以使用绑定到“包围” this
的箭头功能。
.then((docRef) => {
// process this here
})
this
绑定到函数您可以将对象明确绑定到在函数内被视为this
的函数
.then(function(docRef) {
// process this here
}.bind(this))
答案 1 :(得分:1)
执行以下操作:
在您的create_NewUser中:
const that = this;
内部循环使用
that.firestore
.collection('Users-test').doc("/" + docRef.id + "/interests/" + index).add({
......
});
这是因为这不在then的范围内,因此不可引用。
完成:
create_NewUser(data:any){
const that = this;
this.firestore.collection('Users-test').add({
name:data.name,
town:data.town,
gender:data.gender,
email:data.email,
picture:data.picture,
birthdate:data.birthdate
})
.then(function(docRef) {
// console.log("Document written with ID: ", docRef.id);
let nbInterest:any = data.interests.length;
// let nbAvailaibilities:any = data.interests.length;
for (let index = 0; index < nbInterest; index++) {
that.firestore.collection('Users-test').doc("/" + docRef.id + "/interests/" + index).add({
interest:data.interests[index]
})
}
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
绑定也是scorpioo590建议的方式