1

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" class="mat-elevation-z8">
      <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.

R. Richards
  • 23,283
  • 10
  • 63
  • 62
  • What you're looking for is most probably [WebSockets](https://developer.mozilla.org/pl/docs/Web/API/WebSockets_API) on the front-end. How the back-end handles this is a whole different topic, since it very much depends on your tech stack - so you should probably start with making a separate question about that. – TotallyNewb May 30 '22 at 08:14

2 Answers2

0

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

Bipul Jaishwal
  • 259
  • 2
  • 14
0

You can also initialize your variable into ngOnChanges

Sana M.
  • 27
  • 5