Reputation: 746
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!
Upvotes: 0
Views: 553
Reputation: 33345
A few things...
A better way to get the user profile information is to use the uid as the key when you insert the object
firebase.database().ref('/userProfile/' + uid).once("value", function(snapshot){});
If you use =>
fat arrows, the binding is done for you in ionic2
_auth.getUser(this.navParams.get('item').author)
.then((snapshot) => {
// THIS WILL BE WHAT YOU EXPECT...
});
Upvotes: 0
Reputation: 2324
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));
Upvotes: 1