Kyanite Kyanite - 4 months ago 35
AngularJS Question

How to store the result of a Firebase query to a variable from a promise?

I'm new to angular and still trying to get the hang of promises.

I have an ItemDetail class:

@Component({
templateUrl: 'build/pages/item-detail/item-detail.html',
providers: [Auth]
})
export class ItemDetailPage {
private title;
private description;
private author;

constructor(private navParams: NavParams, private _auth: Auth) {
this.title = this.navParams.get('item').title;
this.description = this.navParams.get('item').description;

_auth.getUser(this.navParams.get('item').author).then(function(snapshot){
console.log("ayyy lmao = " + JSON.stringify(snapshot.child(navParams.get('item').author).val().email));
this.author = JSON.stringify(snapshot.child(navParams.get('item').author).val().email);
});

console.log("thisAuthor = " + this.author);
}

}


I'm trying to store the e-mail retrieved from the database as the author variable. Even though it is output correctly in the console, its value does not actually get assigned to the variable outside of the promise. However I think where I'm encountering an issue is to do with the promise, which is a concept I'm still trying to get my head around.

The getUser method in the Auth class is as follows:

getUser(uid: string): any {
return firebase.database().ref('/userProfile').orderByKey().equalTo(uid).once("value", function(snapshot){});
}


If there is a better way to do this (without promises), that'd be a solid alternative too.

Thanks!

Answer

seem like the promise works fine, but this point to wrong instance, use Function.prototype.bind to bind this to ItemDetailPage:

function successHandler(snapshot){ ... };

_auth.getUser(this.navParams.get('item').author).then(successHandler.bind(this));
Comments