Angular9:过滤。为什么在从服务器获取数据时过滤器在 angular material table 中不起作用?

Angular 9: filter. Why the filter does not work in angular material table while fetching data from server?

我刚刚创建了一个 angular material table 但过滤不起作用。

这是我在 angular material 中创建 table 的 HTML 代码:

<mat-form-field>
    <input (keyup)="applyFilter($event)" matInput placeholder="Filter"> 
</mat-form-field>
<table mat-table [dataSource]="dataSource">

    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef> No. </th>
      <td mat-cell *matCellDef="let element"> {{element.id}} </td>
    </ng-container>
  
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>
  
    <ng-container matColumnDef="legal_name">
      <th mat-header-cell *matHeaderCellDef> Legal Name </th>
      <td mat-cell *matCellDef="let element"> {{element.legal_name}} </td>
    </ng-container>
  
    <ng-container matColumnDef="type">
      <th mat-header-cell *matHeaderCellDef> Type </th>
      <td mat-cell *matCellDef="let element"> {{element.type}} </td>
    </ng-container>
  
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

这是我的 JS 代码,我使用我的 settingsService 方法 getAllDomains 从服务器获取数据,它也不适用于排序和分页,但我认为 id 最好先请求过滤然后我决定如果创建排序和分页器会成功:

import { Component, OnInit, ViewChild } from '@angular/core';
import { SettingsService } from 'src/app/smp/service/settings.service';
import { environment as env } from "../../../../../../environments/environment"
import { PageEvent } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';


@Component({
  selector: 'app-domain',
  templateUrl: './domain.component.html',
  styleUrls: ['./domain.component.scss']
})
export class DomainComponent implements OnInit {

  dataSource = new MatTableDataSource();
  pageEvent: PageEvent;
  domains: any;
  displayedColumns: string[] = ['id', 'name', 'legal_name', 'type'];
  headElements = ['ID', 'Name', 'Legal Name', 'Type'];

  constructor(private settingService: SettingsService) {
 
  }

  ngOnInit(): void {
 this.settingService.getAllDomains()
      .subscribe(res => {
        this.domains = res.data.list;
        this.dataSource = this.domains;
      });
      this.dataSource = new MatTableDataSource(this.domains);
  }
  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

}

我的设置服务方法代码:

getAllDomains() {
    return this.http.get<any>(env.apiURL + 'companies');
  }

如下更改您的 ngOnInit

ngOnInit(): void {
    this.settingService.getAllDomains()
         .subscribe(res => {
           this.domains = res.data.list;
           this.dataSource.data = this.domains;
         });
         this.dataSource.data = this.domains;
     }