Typescript:无法更新forEach块内的成员变量

时间:2017-10-22 07:43:24

标签: javascript angular typescript firebase-realtime-database

我正在尝试将值动态推送到构造函数中的数据成员, 但是在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;
}

}

1 个答案:

答案 0 :(得分:0)

您必须初始化availableDrones数组,例如:

public availableDrones: Pickdrone[] = {};

并且为了获得更好的代码,请设置riderProfile类型的常量Pickdrone 为:

      const riderProfile: Pickdrone = {
        name: dataSnap.val().name,
        id: dataSnap.key,
        contact: dataSnap.val().contact,
        email: dataSnap.val().email
      };

以便编译器可以检查您是否为每个属性输入了正确的类型。