1

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.

2
  • 1
    Your http calls are async meaning the code after the calls will continue executing before the calls finishes Commented Apr 23, 2020 at 9:59
  • 1
    the solution is put the forEach INSIDE each subscribe function (yes, you need repeat the instructions -or make an auxiliar function with the two instructions and call it INSIDE the two subscribe-) Commented Apr 23, 2020 at 10:46

1 Answer 1

1

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));
    }
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Can you give me an example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.