Reputation: 1142
I have a Profile Page where I am trying to create a function, retrieveUserData, that will retrieve values from firebase, assign them to variables which I can then use to display in the html file.
import { Component, OnInit, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HomePage from '../../../pages/home/home';
import { AngularFireDatabase } from 'angularfire2/database';
import { Profile } from '../../../models/profile';
import { AngularFireAuth } from 'angularfire2/auth';
@Component({
selector: 'page-profile',
templateUrl: 'profile.html',
})
export class ProfilePage implements OnInit {
name: string = "";
hometown: string = "";
constructor(private afDatabase: AngularFireDatabase, private afAuth: AngularFireAuth, public navCtrl: NavController, private navParams: NavParams) {
}
ngOnInit(){
}
onGoToHome(){
this.navCtrl.push(HomePage)
}
retrieveUserData(){
var userId = this.afAuth.app.auth().currentUser.uid;
}
}
I am trying to pull certain info from the firebase database to assign values to name and hometown and then use them in the html file. I have tried using the following examples from this doc, but the syntax is not working for me.. None of the syntax is being recognized. I know this is super trivial. Can someone help me with a clear example of the proper way to grab this data and use it. The table in firebase is called "profile".
Upvotes: 1
Views: 1185
Reputation: 5272
I think the problem is originating from you referencing the Firebase docs - when you are using the Angularfire2 package... Check out the Angularfire2 documentation here.
In the mean time, I'll provide an example from one of my projects where I query the realtime database via Angularfire2 to help you along:
this.afDatabase.database.ref(`profile/${userId }`).once('value').then( userDetailsAsObject => {
let userDetails = userDetailsAsObject.val() ? userDetailsAsObject.val() : {};
console.log(userDetails);
}).catch( err => {
console.log('Error pulling /profile table inside functionName() inside componentName.component.ts');
console.log(err);
});
EDIT per additional question in comments: Assuming you have this kind of database structure...
profile
|
|--12bd02nasBD0Bd93nbD (userID)
|
|--name:"John Smith"
|
|--hometown:"Paris, France"
Then the database query will return the 12bd02nasBD0Bd93nbD
node as one big object... so you would access properties of that object in the same manner as any other JavaScript object (i.e. dot notation or bracket notation)
this.name = userDetails['name'];
this.hometown = userDetails['hometown'];
Then just reference the name
and hometown
variables in your HTML.
Upvotes: 1