【问题标题】:THEN ARRAY EMPTY PROMISSE [duplicate]然后数组空承诺[重复]
【发布时间】:2019-11-06 13:49:29
【问题描述】:

通过调用 Promise 创建一个在 Firestore 中获取时间的方法,但由于 Promise 尚未解决,因此数组为空。如何解决只有在 getTime() 调用终止时才调用数组。

Angular Cli 8

example.service.ts

teste: [];

getTime() {
    this.userCollection.ref.get()
      .then(res => {
        if (res.docs.length == 0) {
          alert('Não existem marcacoes até o momento por favor aguarde')
        } else {
          res.forEach(ponto => {
            console.log(ponto.id);
            console.log(ponto.data().time.seconds * 1000);
            this.time.push(new Date((ponto.data().time.seconds * 1000)));
          })
        }
      }).catch(err => {
        console.log(err);
      })
  }
example.component.ts

ngOnInit() {
    this.mainService.getTime();
    console.log(this.mainService.time);
  }

希望我调用的时候数组变量已经完整了。

【问题讨论】:

  • getTime 应该返回一些东西(一个 Promise)并且你应该等待它(使用.then())。

标签: javascript angular typescript firebase google-cloud-firestore


【解决方案1】:

您可以使用asyncawait

服务中。

getTime() {
    return this.userCollection.ref.get()
      .then(res => {
        if (res.docs.length == 0) {
          alert('Não existem marcacoes até o momento por favor aguarde')
        } else {
          res.forEach(ponto => {
            console.log(ponto.id);
            console.log(ponto.data().time.seconds * 1000);
            this.time.push(new Date((ponto.data().time.seconds * 1000)));
          })
        }
        return true;
      }).catch(err => {
        console.log(err);
      })
  }

在组件中,

async ngOnInit() {
    await this.mainService.getTime();
    console.log(this.mainService.time);
}

【讨论】:

    猜你喜欢
    • 2018-03-19
    • 2021-04-01
    • 2015-04-15
    • 2020-11-25
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多