每當我運行以下代碼時,從checkIfUserHasMadeBet()函數返回的值始終爲空。看起來代碼並沒有等待函數返回值,而是跳過了前面。如何讓它等待函數從Firebase數據庫返回數據?爲什麼始終從functio返回的值爲null或未定義?
export class DisplayBetPage {
hasCurrentUserMadeAbet: boolean = false;
constructor(private navParams: NavParams, public navCtrl: NavController, private afAuth: AngularFireAuth, private afDatabase: AngularFireDatabase, public alertCtrl: AlertController) {
}
ionViewWillLoad() {
var temp = this.checkIfUserHasMadeBet();
console.log(temp); // comes out as null
if (temp != null) {
this.hasCurrentUserMadeAbet = true;
}
}
checkIfUserHasMadeBet() {
this.afAuth.authState.take(1).subscribe(auth => {
this.afDatabase.database
.ref(`userprofile/${auth.uid}/bets/${this.bettingKey}`)
.once(`value`).then(function(snapshot) {
console.log(snapshot.val());
// comes out with correct value [not null]
return snapshot.val();
});
});
}
}
在observable中還有嵌套的異步調用,這使得很難處理。我建議OP在RxJS上閱讀其操作員的權力,以便毫無問題地使用它們。 –
好的,非常感謝,所以我如何使它異步等待電話完成? –
@AdamGoldberg更新了你如何獲得價值的藍圖 –