0

I am using Angular 4 and angularfire with Firebase database.I have the following Firebase database

"questions" : {
"tv" : {
  "got" : {
    "1" : {
      "answer1" : "Death",
      "choice11" : "Exile",
      "choice12" : "You lose a hand",
      "choice13" : "You lose the privilege to marry and father children",
      "description" : "",
      "q1title" : "What is the punishment for deserting the Night’s Watch?"
    },
    "questions" : {
      "number" : 1
    }
  }
}
}

And I want to read the question number on the button and pass it to my program to use it on functions etc.I am currently using this part of code to read it

constructor(public afAuth: AngularFireAuth, public af: AngularFireDatabase,public authService: AuthService,
              private router: Router) {
    var ref = firebase.database().ref("questions/tv/got/questions");
    ref.once("value")
      .then(function(snapshot) {
        let qnumber = snapshot.child("number").val(); 
        console.log(qnumber);
      });
  } 

Everything works fine and I can see the qnumber on the concole(qnumber=1).However I can't pass the qnumber on the program and use it for my other functions I tried to declare a second variable like and give it the qnumber value like this

    qnumber2;
  constructor(public afAuth: AngularFireAuth, public af: AngularFireDatabase,public authService: AuthService,
              private router: Router) {
    var ref = firebase.database().ref("questions/tv/got/questions");
    ref.once("value")
      .then(function(snapshot) {
        let qnumber = snapshot.child("number").val(); 
        this.qnumber2 = qnumber;
        console.log(qnumber2);
      });

But I get errors on compiler.Can you help me and tell my a way to pass the qnumber on my program as an integer?

Vasilis Michail
  • 403
  • 2
  • 6
  • 17

1 Answers1

0

Try this :

qnumber2;constructor(public afAuth: AngularFireAuth, public af: AngularFireDatabase,public authService: AuthService,
          private router: Router) {
var ref = firebase.database().ref("questions/tv/got/questions");
ref.once("value")
  .then((snapshot) => {// ** My only change ** or use snapshot
    let qnumber = snapshot.child("number").val(); 
    this.qnumber2 = qnumber;
    console.log(qnumber2);
  });

The this keyword refers to the object the function belongs to, or the window object if the function belongs to no object.In JavaScript a function is an object. for more on this inside a function

In your case this.qnumber2 is not the global one , it's scope is limited to the function it is used. If you don't use any function then this will refer to the global object.

Satish Kumar
  • 601
  • 6
  • 14