Akash Rao
Akash Rao

Reputation: 928

Firebase child_added `this` is not working

I am developing a chat application using Angular2, ionic2 and firebase. To get the chats i tried the below method

Controller code:

displayAllMessage() {
    let myDataRef = new Firebase("firbaseurl");
    myDataRef.on('child_added', function(snapshot) {
      this.message = snapshot.val();
      console.log(this.message);
    });
  }

View Code :

<h1> {{message.text}} </h1>

but the problem here is - if I use this.message it is throwing the error saying this.message is undefined and if I use var message instead of this then it works fine. if I use var message then I can't display it in the view.

Thank you in advance.

Upvotes: 0

Views: 799

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657536

Use the arrow function () => { ... } instead of function () { ... } to retain the scope of this.

  displayAllMessage() {
    let myDataRef = new Firebase("firbaseurl");
    myDataRef.on('child_added', (snapshot) => {
      this.message = snapshot.val();
      console.log(this.message);
    });
  }

See also https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

  displayAllMessage() {
    let myDataRef = new Firebase("firbaseurl");
    myDataRef.on('child_added', function (snapshot) {
      this.message = snapshot.val();
      console.log(this.message);
    }.bind(this));
  }

Upvotes: 6

Pratik Kelwalkar
Pratik Kelwalkar

Reputation: 1632

Same situation another scenario, its a issue of (this). Since your this will refer to context of the callback function

...function(snapshot) {
      this.message = snapshot.val();
      console.log(this.message);
    });

it wont be able to find the variable message. The solution to this is pass the reference(this) to the outer method and then access it in your callback. So your code would look like.

displayAllMessage(parentRef : any) {
    let myDataRef = new Firebase("firbaseurl");
    myDataRef.on('child_added', function(snapshot) {
      parentRef.message = snapshot.val();
      console.log(parentRef.message);
    });
  }

and call the method displayAllMessage(this); instead of displayAllMessage();

Upvotes: 2

Related Questions