![](/img/trans.png)
[英]AngularFire - How to map firestore documents to an array on valueChanges?
[英]How to get multiple random documents from angularfire firestore
我一直在尋找解決方案,但不適用於我的應用程序,我正在嘗試使用 angularfire 和 firestore 構建一個測驗應用程序,我目前的方法是:
public getRandomQuestion(): Promise<any> {
let ques: IQuestion;
return this.firestore.collection('questions', ref => ref.where('randId', '>=', this.getRandomInt(1,999999)).limit(1)).valueChanges().toPromise();
}
public getTenRandomQuestion(): IQuestion[]{
let obs : IQuestion[] = [];
for (let i: number = 0; i <= 9; i++){
this.getRandomQuestion().then(res => {
obs[i] = res;
});
}
console.log(obs);
return obs;
}
但它總是返回一個空數組,這是我的 firestore: Firestore
如果您添加一些日志記錄或在調試器中運行代碼,您可以很容易地看到您的return obs
在obs[i] = res
被調用之前運行。
這就解釋了為什么你總是得到一個空數組,你的getTenRandomQuestion
方法在從數據庫加載任何數據之前結束。
解決方案是返回一個Promise
,就像你從getRandomQuestion
做的那樣。
public getTenRandomQuestion(): Promise<IQuestion>[]{
let obs : Promise<IQuestion>[] = [];
for (let i: number = 0; i <= 9; i++){
obs[i] = this.getRandomQuestion();
}
return obs;
}
然后當您調用getTenRandomQuestion
,您要么添加then()
子句,要么使用async
和await
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.