2017-02-20 24 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); 
}