angularangular-materialangular-material-table

Continuously update the data in the Angular Material tables from an API


I have an Angular app in which I created a table using Angular Material and filling the data using an API. My code


  ngOnInit() {
    this.getChillerApiData();
  }

  getChillerApiData() {
    this.api.getFirstChillerData()
      .subscribe((first_data:any) => {
        this.first_api_data = first_data;
        this.putPrimaryPumpData();
      });
  }

  displayedColumns_primary_pump: string[] = ['Index', 'Pump', 'Frequecy', 'Mode'];
  dataSource_primary_pump = new MatTableDataSource<PrimaryPumpDataTable>()

  primary_pump_index = 1
  @ViewChild('table', { static: true }) primary_pump_table
  putPrimaryPumpData(){
    this.dataSource_primary_pump.data.push(
      {Index: this.primary_pump_index++, Pump: "P-1", Frequecy: String(this.first_api_data["Pr. Chw Pump 1 VFD F/B"]), Mode: String(this.first_api_data["Pr. Chw Pump 1 A/M status"])},
      {Index: this.primary_pump_index++, Pump: "Delta T", Frequecy: String(this.first_api_data["Chiller 1 evap Supply temp"] - this.first_api_data["Chiller 1  evap ret Temp"]).slice(0,4), Mode: ""},)
      this.primary_pump_table.renderRows();
  }

}

I am trying to fetch the data in ngOnIt and display it in table. I want this data to be updated every 1 minute, by making API call every 1 minute. For that, I have added a function like

intervalId : any

  getRealTimeData() {
    this.getChillerApiData()
    clearInterval(this.intervalId);
    this.intervalId = setInterval(() => {
      this.getChillerApiData();
    }, 1000);
  }

and calling this function in ngOnIt. Now I am able to get the latest data, but rows in my table are being appended with the new data. I want to update the rows in the table with the latest values from API instead of adding new rows.

What can I try to achieve this?


Solution

  • If you want to simply replace the data do

    putPrimaryPumpData(){
        this.dataSource_primary_pump.data = [
          {Index: this.primary_pump_index++, Pump: "P-1", Frequecy: String(this.first_api_data["Pr. Chw Pump 1 VFD F/B"]), Mode: String(this.first_api_data["Pr. Chw Pump 1 A/M status"])},
          {Index: this.primary_pump_index++, Pump: "Delta T", Frequecy: String(this.first_api_data["Chiller 1 evap Supply temp"] - this.first_api_data["Chiller 1  evap ret Temp"]).slice(0,4), Mode: ""}
        ]
          this.primary_pump_table.renderRows();
      }