Ramesh
Ramesh

Reputation: 1155

requesting http.post in a loop not working in Angular

I have below code that requests http.post in a loop of 100 elements but saving the data in DB only for first one or two records, remaining gets internal server error.

post(data: any): Observable<any> {
    return this.http.post(myUrl, data);
  }

myMethod() {
  for (let i = 0; i < this.myJSON.length; i++) { // 100 elements
    // Some Business Logic and changing myForm values
    this.post(this.myForm.value).subscribe( dd => { this.saved++; });
  }
}

I tried with but no luck.

setTimeout(() => {
          this.post(this.myForm.value).subscribe( dd => { this.saved++; });
        }, 1000);

My environment is Asp.Net Core 2.2 and Angular8. C# method is async.

How can I post all 100 elements in a loop?

Upvotes: 0

Views: 259

Answers (2)

Ivan Frolov
Ivan Frolov

Reputation: 103

Internal server error is a server error. I woul consider to make one request and perform saving of all elements on a server side

Upvotes: 1

Federico Ibba
Federico Ibba

Reputation: 128

The best way to handle multiple request is using forkJoin by rxjs. A forkJoin takes in input an array of Observable, then it returns a response when every request is complete. In this case:

 post(data: any): Observable<any> {
    return this.http.post(myUrl, data);
  }

  myMethod() {
    let callsToPerform: Observable<any>[] = [];
    for (let i = 0; i < this.myJSON.length; i++) { // 100 elements
      // Some Business Logic and changing myForm values
      callsToPerform.push(this.post(this.myForm.value));
    }

    forkJoin(callsToPerform)
      .subscribe(arrayOfResults => {
        // some operations
      })
  }

Upvotes: 0

Related Questions