从Firebase检索用户信息并在应用中显示

时间:2018-06-17 21:23:55

标签: angular firebase ionic-framework firebase-realtime-database

我有一个配置文件页面,我正在尝试创建一个函数,retrieveUserData,它将从firebase检索值,将它们分配给变量,然后我可以使用它来显示在html文件中。

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;


  }

}

我试图从firebase数据库中提取某些信息,以便为name和hometown分配值,然后在html文件中使用它们。我尝试使用this doc中的以下示例,但语法对我不起作用。没有语法被识别。我知道这是非常微不足道的。有人可以帮我一个明确的例子来获取这些数据并使用它。 firebase中的表名为" profile"。

1 个答案:

答案 0 :(得分:1)

我认为问题源于您引用Firebase文档 - 当您使用Angularfire2软件包时...查看Angularfire2 documentation here

与此同时,我将从我的一个项目中提供一个示例,我通过Angularfire2查询实时数据库,以帮助您:

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

在评论中每增加一个问题编辑: 假设你有这种数据库结构...

profile
   |
   |--12bd02nasBD0Bd93nbD    (userID)
          |
          |--name:"John Smith"
          |
          |--hometown:"Paris, France"

然后数据库查询将12bd02nasBD0Bd93nbD节点作为一个大对象返回...因此您将以与任何其他JavaScript对象相同的方式访问该对象的属性(dot notation or bracket notation

this.name = userDetails['name'];
this.hometown = userDetails['hometown'];

然后只需引用HTML中的namehometown变量。

相关问题