0
コンストラクタ内のデータメンバーに値を動的にプッシュしようとしましたが、のforEachブロック内にそのメンバーにアクセスできません。Typescript: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'コンテキストを保持するローカル変数を作成してください。 – Icepickle
ローカル変数を作成するには、矢印関数を使用します。 [typescriptlang](https://www.typescriptlang.org/docs/handbook/functions.html) – Philipp
@Icepickleで、この機能と矢印機能の章をご覧ください。それは問題でした。しかし今、プッシュは未定義であると言っています。あなたはそれで私を助けることができますか? – Vinayak