【发布时间】:2026-01-17 21:05:01
【问题描述】:
我正在尝试将值动态推送到构造函数中的数据成员, 但在 forEach 块内,我无法访问该成员。
这里AppComponentClass
export class AvailableRidersComponent {
public availableDrones: Pickdrone[];
constructor() {
const db = firebase.database();
const availableRidersRef = db.ref('/riders/active_riders/available/');
availableRidersRef.on('value', snapshot => {
snapshot.forEach(function (childSnapshot) {
const riderProfileRef = db.ref('/riders/Pickdrones/' + childSnapshot.key);
riderProfileRef.on('value', dataSnap => {
const riderProfile = {
name: dataSnap.val().name,
id: dataSnap.key,
contact: dataSnap.val().contact,
email: dataSnap.val().email
};
console.log(riderProfile); //Prints values properly
this.availableDrones.push(riderProfile); //ERROR TypeError: Cannot read property 'availableDrones' of undefined
});
});
});
}
}
这里是我的Pickdrone 课程
export class Pickdrone {
public name: string;
public id: string;
public contact: string;
public email: string;
// vehicleType: string;
constructor(name: string, id: string, contact: string, email: string){
this.name = name;
this.contact = contact;
this.id = id;
this.email = email;
}
}
【问题讨论】:
-
this在回调中将不再是您的类,如果没有绑定,请在向数据库发起请求之前创建一个包含this上下文的局部变量,以便您可以使用本地回调中的变量 -
另外,要创建局部变量,您可以使用箭头函数。看看
this and arrow functions的章节typescriptlang -
@Icepickle 谢谢,这就是问题所在。但现在它说推动是未定义的。你能帮我吗?
标签: javascript angular typescript firebase-realtime-database