简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM