Tony
Tony

Reputation: 550

Firebase 3 - Ionic 2 - .on('value' , snapshot => { this...} this is null

When I try to retrieve data using Firebase 3 SDK for Web, "this" is showing as null. Any idea why this might occur ?

this.mainApp = firebase.initializeApp(config);
FBGet(path){
    return this.mainApp.database().ref(path);
}
...
GetUser(){
    this.appData.FBGet('users/'+user.uid).on('value', function(snapshot) {
        var objUser = snapshot.val();
        //the following statement is throwing an exception cause 'this' is null
        this.events.publish('user:update', objUser);
    });
}

Thank you

Upvotes: 0

Views: 863

Answers (1)

David East
David East

Reputation: 32624

You're not using an arrow function for FBGet, so this will not be bound to your component/provider.

GetUser(){
  this.appData.FBGet('users/'+user.uid).on('value', (snapshot) => {
    const objUser = snapshot.val();
    // this is now bound to the component using the fat arrow =>
    this.events.publish('user:update', objUser);
  });
}

The above solution will only work if this.events is a property on the same component/provider.

Upvotes: 1

Related Questions