0

I have an observable, what get all boxes from server. Every boxes has a property(lastUpdateBy), what I want to change to a full name from userservice. The problem is, Ag-grid always show the result much sooner, then data changes. After refresh the grid, data appear properly. Any idea, what is the problem here? Thanks

getAllBox() {
    this.BoxesService.getAllBoxes().subscribe(responseData => {
      responseData.Boxes.map(item => {
        this.userService
          .getUserName(item.lastUpdatedBy)
          .subscribe(fullName => {
            item.lastUpdatedBy = fullName
          })
      })
      this.agGridData = responseData.boxes
    })
  }
Piyush Jain
  • 1,895
  • 3
  • 19
  • 40
gbrvrg
  • 53
  • 5
  • You are making API call for each item of `responseData.Boxes` in `map` function. Is it okay? Try to get all necessary info just in one API call. – StepUp Sep 16 '19 at 13:16
  • Yes, it is ok.. – gbrvrg Sep 16 '19 at 13:20
  • are you able to make one API call to get all necessary info? – StepUp Sep 16 '19 at 13:21
  • Instead of nesting your subscriptions, I would recommend you to use RxJS operators such as mergemap. Here is an example of how it can be done (https://stackoverflow.com/questions/56572705/angular-7-nesting-observables/56572761#56572761) – wentjun Sep 16 '19 at 16:27

1 Answers1

0

If you are not allowed to make just one WEB API call, then you can check if there is other items in array and if there is no items in array, then just show grid:

HTML:

<ag-grid-angular 
    *ngIf="showData"
    style="width: 500px; height: 500px;" 
    class="ag-theme-balham"
    [rowData]="yourRows" 
    [columnDefs]="yourColumns"
    >
</ag-grid-angular>

TypeScript:

showData: Boolean = false;

getAllBox() {

    this.BoxesService.getAllBoxes().subscribe(responseData => {
        let boxMaxIndex = responseData.Boxes.length - 1;
        responseData.Boxes.map((item, index) => {
            this.userService
            .getUserName(item.lastUpdatedBy)
            .subscribe(fullName => {
              item.lastUpdatedBy = fullName
              if (boxMaxIndex === index)
                this.showData = true;
            })
        })
        this.agGridData = responseData.boxes
      })
}
StepUp
  • 36,391
  • 15
  • 88
  • 148