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.

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

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

Jason
Guest

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();