angular 4从firebase检索数据

时间:2018-04-27 07:33:04

标签: angular firebase

我尝试从firebase中检索数据,但是我得到了未定义的值

服务代码是

  getUserData():any{

  var that = this;

 firebase.database().ref('/users/').once('value').then(function(snapshot) {
  console.log("service UserData = "+ JSON.stringify(snapshot.val()) );
    return  snapshot.val();
        })  }

家庭代码就是这个

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { UserDataProvider } from '../../providers/user-data/user-data';
import * as firebase from 'firebase';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

    UserData1:any;

  constructor(public navCtrl: NavController,private userDateService: UserDataProvider) {

      this.UserData1 =   this.userDateService.getUserData();
      console.log("home UserData = "+ JSON.stringify(this.UserData1) ); 
  }
}

以下代码从firebase返回值,结果显示在控制台

console.log("service UserData = "+ JSON.stringify(snapshot.val()) );

{"city":"iii","email":"iii@iii.com","first_name":"iii","isWorking":"","last_name":"iii","phone":"i","skills":"iiii","state":"ii"}

下面的代码从firebase返回未定义的值,结果显示在控制台

console.log("home UserData = "+ JSON.stringify(this.UserData1) ); 

home UserData = undefined

1 个答案:

答案 0 :(得分:0)

您没有在getUserData函数中返回数据。试试下面的代码

 getUserData():any{

var that = this;

   return firebase.database().ref('/users/').once('value').then(function(snapshot) {
      console.log("service UserData = "+ JSON.stringify(snapshot.val()) );
        return  snapshot.val();
})  }