打字稿:遍历数组不起作用吗?

时间:2020-04-23 09:54:08

标签: javascript angular typescript

在我的源代码中,我从http.get调用中接收了一些数据。当我尝试在控制台中写入每个“正式”的状态时,什么也没有发生。我的错误在哪里?

fillTable(): void {
console.log('fillTable');
this.formulare = [];
if (this.ansichtAuswahl === this.ansichten.ALLE) {
  this.formularService.getAll().subscribe(formular =>
      this.formulare = formular,
    error => console.log(error));
} else {
  this.formularService.getMy().subscribe(formular =>
      this.formulare = formular,
    error => console.log(error));
}
this.formulare.forEach( (element) => {console.log(element.status); });
this.filterStatus();}

公式数组已填充,因为网站上的表也已填充,但没有控制台输出。

1 个答案:

答案 0 :(得分:1)

将forEach移动到subscription块中,因为当您遍历元素时,http请求仍在进行中。可观察对象是异步的:

  fillTable(): void {
    console.log('fillTable');
    this.formulare = [];
    if (this.ansichtAuswahl === this.ansichten.ALLE) {
      this.formularService.getAll().subscribe(formular =>
        {
          this.formulare = formular;
          this.formulare.forEach( (element) => {console.log(element.status); });
          this.filterStatus();
        },
        error => console.log(error));
    } else {
      this.formularService.getMy().subscribe(formular =>
        {
          this.formulare = formular;
          this.formulare.forEach( (element) => {console.log(element.status); });
          this.filterStatus();
        },
        error => console.log(error));
    }
  }