0

I am trying to push values dynamically to my data member inside the constructor, but inside the forEach block, I'm not able to access that member.

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

and here us my Pickdrone class

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

}

Vinayak
  • 13
  • 6
  • `this` in a callback won't be your class anymore without binding, create a local variable that holds the `this` context before firing the request to the database, so that you can use the local variable inside your callback – Icepickle Oct 22 '17 at 07:48
  • Alternatively, to creating a local variable, you can use arrow functions. Have a look at the chapter `this and arrow functions` over at [typescriptlang](https://www.typescriptlang.org/docs/handbook/functions.html) – Philipp Oct 22 '17 at 07:56
  • @Icepickle thank you, That was the problem. but now it's saying that the push is undefined. can you help me with that? – Vinayak Oct 22 '17 at 07:57

1 Answers1

0

you have to initialize your availableDrones array , like this for example:

public availableDrones: Pickdrone[] = {};

and also for better code, make the constant riderProfile of type Pickdrone as:

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

so that the compiler can check if you input the correct type for each property.

Ebraheem Alrabeea
  • 2,130
  • 3
  • 23
  • 42