Home > Blockchain >  How to Update Mat-Table Data automatically without refresh when Data changes in SQL DB?
How to Update Mat-Table Data automatically without refresh when Data changes in SQL DB?

Time:05-30

I want to get live data into my Mat-table grid without refreshing the page when i make changes in the SQL Database .

I am trying with Observables and subscribing to it but it doesnt auto refresh and give the live data .

My Component -

    getDataForClients(name:string){
    this.dashboardService.getClientsData(name).subscribe(res=>{
      this.dataSource = new MatTableDataSource(res);
  })

My Service -

 public getClientsData(name:string){
  return this.http.get<any[]>('https://localhost:44395/api/StocksOrders/'   name);
}

M HTML -

<table mat-table [dataSource]="dataSource" >
      <ng-container matColumnDef="stockName">
        <th mat-header-cell *matHeaderCellDef> Stock Name </th>
        <td mat-cell *matCellDef="let element"> {{element.stockName}} </td>
      </ng-container>
    
     
      <ng-container matColumnDef="quantity">
        <th mat-header-cell *matHeaderCellDef> Quantity </th>
        <td mat-cell *matCellDef="let element"> {{element.quantityPurchased}} </td>
      </ng-container>
    
     
      <ng-container matColumnDef="purchaseDate">
        <th mat-header-cell *matHeaderCellDef> Purchase Date </th>
        <td mat-cell *matCellDef="let element"> {{element.quantityPurchased}} </td>
      </ng-container>
    
     
      <ng-container matColumnDef="purchasePrice">
        <th mat-header-cell *matHeaderCellDef> Purchase Price </th>
        <td mat-cell *matCellDef="let element"> {{element.stockPurchasePrice}} </td>
      </ng-container>

      <ng-container matColumnDef="currentPrice">
        <th mat-header-cell *matHeaderCellDef> Current Price </th>
        <td mat-cell *matCellDef="let element"> {{element.stockCurrentPrice}} </td>
      </ng-container>
    
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>

What changes will I have to do to achieve that ? Please help.

CodePudding user response:

It has been answered already here

I don't know if the ChangeDetectorRef was required when the question was created, but now this is enough:

import { MatTableDataSource } from '@angular/material/table';

// ...

dataSource = new MatTableDataSource<MyDataType>();

refresh() {
  this.myService.doSomething().subscribe((data: MyDataType[]) => {
    this.dataSource.data = data;
  }
}

You may check here as well.

Example: StackBlitz

CodePudding user response:

You can also initialize your variable into ngOnChanges

  • Related