Christopher Feldhues
Christopher Feldhues

Reputation: 37

Typescript: Iterate over Array doesn't work?

In my source code, i recieve from a http.get call some data. When i try to write the status of each 'formular' in the console, nothing happens. Where is my mistake?

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

The formular array is filled, because the table on the website is filled too, but there is no console output.

Upvotes: 1

Views: 85

Answers (1)

Marius Orha
Marius Orha

Reputation: 670

Move the forEach in subscribe block, because when you iterate through the elements, the http request is still in progress. The observables are asynchronous:

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

Upvotes: 1

Related Questions