0

I am using Anular9 and using mat-raised-button as below:

  <button mat-raised-button (click)="saveClick()" color="primary"><mat-icon>check</mat-icon>&nbsp;&nbsp;Ok</button>

The saveClick() is defined as below

saveClick() {
    for (let i = 0; i < this.hostid.length; i++) {
        const saudit: SInterface = {
            data: this.data,
            eid: this.eid[i],
            serverId: this.hostid[i]
        };
        this.subs.sink = this.sservice.addRecord(saudit)
            .subscribe(s => {
                this.dialog.close();
            });
    }

}

Here datais common for all the records.

The above code is only saving the first record with i=0. How to change saveClick() so that it saves all records until i < this.hostid.length?

meallhour
  • 13,921
  • 21
  • 60
  • 117

1 Answers1

1

H.

Rather than using for loop, try using map, once you will have array of saudits then call your service with it as a param.

BTW. Move your call to service outside of the loop / map.

** Edit I don't know your business logic exactly, but I would use that mapping at least as strting point.

    // Map each Id in the hostid array to SInterface
    const saudits: SInterface = this.hostid.map((id, index) => {
      return {
        data: this.data,
        eid: this.eid[index],
        serverId: id,
      } as SInterface;
    });

    // Pass all saudits at once to service
    this.sservice.addRecord(saudits).subscribe(...);
Space
  • 178
  • 2
  • 10