THEN ARRAY EMPTY PROMISSE [duplicate]

2019-09-27 15:51发布

Create a method to fetch time in the firestore by calling the promise, but the array comes empty because the promise has not yet been resolved. How to resolve to call the array only when a getTime () call terminates.

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

I hope the array variable is already complete when I call it.

1条回答
等我变得足够好
2楼-- · 2019-09-27 16:19

You can use async and await.

In service.

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

In component,

async ngOnInit() {
    await this.mainService.getTime();
    console.log(this.mainService.time);
}
查看更多
登录 后发表回答