0

我有一个 Mat 表,它通过 Http get 获取数据。我最初在页面加载后填充表格,然后在搜索完成时填充表格。我的表最初被填充,但是当数据源更新时,表没有用更新的数据呈现。我正在使用 subject 来监听任何变化。我可以在控制台中看到更新的值。

export class SearchTableComponent implements OnInit {

   displayedColumns = ['claim', 'firstName', 'dateOfBirth'];

   isBusy: boolean
   _persons : person[] =[];
   personObservalbe$ = new Subject<person[]>();
   constructor(private personexternalservice: PersonExternalService) { }

   ngOnInit() {
     this.getPersons('','','','');//to load first 100 rows when the 
       pageloads 

     this.personObservalbe$.subscribe((result:person[])=>{
     console.log('init1');
     console.log(result);
     this.dataSource = new MatTableDataSource(result);

    });
 }


   //function called on button click  
  getPersons(searchClaim, Dob, lName, fName) {

   let searchClaimNo = searchClaim;
   let searchDOB = Dob;
   let searchSurname = lName;
   let searchFirstname = fName;
   var sDOB = "";

   this.isBusy = true;

  if (searchClaimNo == '')
    searchClaimNo = "empty";

  if (sDOB == '')
    sDOB = "empty";

 if (searchSurname == '')
   searchSurname = "empty";

 if (searchFirstname == '')
   searchFirstname = "empty";

 this.personexternalservice._searchForPeson(searchClaimNo, sDOB, searchSurname, searchFirstname)
  .subscribe( ( person$  => {
   this.personObservalbe$.next(person$);
   console.log(person$);
  })
 );

}

export class person {
  coalServicesId: string;
  firstName: string;
  lastName: string;
  pctId: string;
  claim: string;
  dateOfBirth: string;
}

// Service called
_searchForPeson(claimsNo:string, DOB:string, surname:string, 
  firstName:string):Observable<any> {
    return this.http.get(`api/Mockup/Search/${claimsNo}/${DOB}/${surname}/${firstName}`);
}

HTML <mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <ng-container matColumnDef="claim"> <mat-header-cell *matHeaderCellDef>Claim</mat-header-cell> <mat-cell *matCellDef="let element">{{element.claim}}<a fxFlexFill class="mat-row-link"></a></mat-cell> </ng-container> <ng-container matColumnDef="firstName"> <mat-header-cell *matHeaderCellDef>Name</mat-header-cell> <mat-cell *matCellDef="let element">{{element.firstName}} {{element.lastName}}</mat-cell> </ng-container> <ng-container matColumnDef="dateOfBirth"> <mat-header-cell *matHeaderCellDef>Date Of Birth</mat-header-cell> <mat-cell *matCellDef="let element">{{element.dateOfBirth}}</mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row routerLink="" *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table>

4

1 回答 1

0

您需要将结果集设置为 dataSource,而不是在 subscribe 中创建对象。然后也刷新一下。

this.personObservalbe$.asObservable().subscribe((result:person[])=> {
   this.dataSource.data = result; 
   this.table.renderRows(); 
});

显然,全局声明和初始化数据源。也声明 ViewChild。

dataSource = new MatTableDataSource();
@ViewChild(MatTable) table:

也更新html。

<mat-table #table [dataSource]="dataSource" class="mat-elevation-z8">
于 2019-03-28T04:37:20.273 回答