2

I wrote a function to check if there is a data saved in "phonenumber" child on my firebase database or not .. the tests are OKEY! but inside this function I can't call an external declared variable ! this is code:

phoneNumberExistence: boolean;

FIREBASE_DATABASE.ref("Settings").child('phoneNumber').once('value', function(snapshot) {
      var exists = (snapshot.val() !== null);
      //console.log("Phone number existance: "+exists);
      if(exists){
        this.phoneNumberExistence = true; //the problem is here.. can't use this variable
        console.log("A phone number already exists.")
      }
      else{
        this.phoneNumberExistence = false; //the problem is here.. can't use this variable
        console.log("There is no phone number here :(");
      }
    })

Any idea ? thanks

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Arselan
  • 45
  • 5

1 Answers1

0

Use arrow functions instead of function(snapshot) {...}

... .once('value', (snapshot) => {
  var exists = (snapshot.val() !== null);
  ...
});

Arrow Functions lexically bind their context so this actually refers to the originating context. For more details, you can read this article.

shohrukh
  • 2,989
  • 3
  • 23
  • 38