简体   繁体   中英

How to get multiple random documents from angularfire firestore

I've been looking for solutions but non worked for my application, I'm trying to build a Quiz app using angular and firestore with angularfire, my current approach:

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;
}

But it always returns an empty array, here's my firestore : Firestore

If you add some logging or run the code in a debugger, you can most easily see that your return obs runs before the obs[i] = res is ever called.

So that explains why you always get an empty array, your getTenRandomQuestion method ends before any data has been loaded from the database.

The solution is to return a Promise , just like you do from getRandomQuestion .

  public getTenRandomQuestion(): Promise<IQuestion>[]{
    let obs : Promise<IQuestion>[] = [];
    for (let i: number = 0; i <= 9; i++){
      obs[i] = this.getRandomQuestion();
    }
    return obs;
  }

And then when you call getTenRandomQuestion , you either add a then() clause, or you use async and await .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM