2017-02-20 83 views
0

我正在尝试从firebase读取值并将其分配给全局变量,但它无效。如何将从firebase读取的值赋给变量

public points: any; 

    readPoints(): any{ 
     this.userProfile.child(this.user.uid).once('value').then((snapshot) =>{ 
      this.points = snapshot.val().user_points; 
     }); 
    } 
    console.log(this.points); //undefined 




Users{ 
      SAdS4cW57DSLuWr2obbZYUHsmAL2{ 
       user_points: 20 
..... 
+0

可以更新你与你的数据库结构为例问题吗? –

+0

我加了db结构 –

回答

2

那么,你的变量是this.points但你要打印this.point

+0

这不是问题!我只是在这里输入错误因为我没有从代码复制! –

0

你的代码似乎我的权利,请尝试打印snapshot.val(),看看它给你。我只是添加一个代码,我想象你的完整数据库查询是。

firebase.database().ref('Users/').child(this.user.uid).once('value').then(snapshot => { 
    this.points = snapshot.val().user_points; 
}) 

它是否给控制台带来任何错误?它是否获得了this.user.id对不对?

+0

不!它没有给出任何错误! –

1

我读这article从火力和看起来像解决方法是调用另一个函数,而不是分配价值直接变量

public points: any; 

readPoints(): any{ 
    this.userProfile.child(this.user.uid).once('value').then((snapshot) =>{ 
     this.getPoints(snapshot.val().user_points); 
    }); 

} 
getPoints(point: any = null): any{ 
    this.points = parseInt(point) + 20; 
    console.log("point="+ this.points); 
}