【问题标题】:How to get multiple random documents from angularfire firestore如何从 angularfire firestore 获取多个随机文档
【发布时间】:2021-07-22 04:29:43
【问题描述】:

我一直在寻找解决方案,但不适用于我的应用程序,我正在尝试使用 angular 和带有 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

【问题讨论】:

    标签: angular typescript google-cloud-firestore


    【解决方案1】:

    如果您添加一些日志记录或在调试器中运行代码,您可以很容易地看到您的 return obsobs[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() 子句,要么添加use async and await

    【讨论】:

    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 2020-07-29
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多