使用ajax调用

时间:2018-03-12 07:32:10

标签: angular angular-material2 angular-material-5

使用Ajax从后端获取值后,排序和分页无效。

我正在使用以下版本:

Angular:5.2.7 材料:5.2.4 TypeScript:2.5.3

我的代码段:

<div class="form-created-by-me-header">
        <mat-form-field>
            <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
        </mat-form-field>
    </div>

    <div class="form-created-by-me-container mat-elevation-z8">

        <mat-table [dataSource]="dataSource" matSort>

            <!-- ID Column -->
            <ng-container matColumnDef="id">
                <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>
                <mat-cell *matCellDef="let row"> {{row.id}} </mat-cell>
            </ng-container>

            <!-- Name Column -->
            <ng-container matColumnDef="name">
                <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
                <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;">
            </mat-row>
        </mat-table>

        <mat-paginator [pageSizeOptions]="[1, 5, 10, 25, 100]"></mat-paginator>

    export class FormCreatedByMeComponent {

      cratedFormsByMe: Array<SurveyForm>;
      dataSource: MatTableDataSource<SurveyForm> = new MatTableDataSource();


      public displayedColumns = ['id', 'name', 'description', 'questionCount', 'sharedWith', 'createdBy', 'createdDate', 'editBtn', 'deleteBtn'];

      @ViewChild(MatPaginator) paginator: MatPaginator;
      @ViewChild(MatSort) sort: MatSort;

      constructor(private formService: SurveyFormService) {
        this.getCreatedFormsByMe();
      }

      private getCreatedFormsByMe(): void {
        this.formService.getCreatedFormsByMe().subscribe(
          cratedFormsByMe => {
            this.cratedFormsByMe = cratedFormsByMe;
            this.dataSource = new MatTableDataSource(this.cratedFormsByMe);
            this.dataSource.paginator = this.paginator;
            this.dataSource.sort = this.sort;
          });
      }


      applyFilter(filterValue: string) {
        filterValue = filterValue.trim(); // Remove whitespace
        filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
        this.dataSource.filter = filterValue;
      }

    }

在上述情况下,没有任何事情发生。如果我遗漏任何东西,请纠正我。

2 个答案:

答案 0 :(得分:4)

我通过在分页器和分拣机周围添加超时解决了这个问题:

setTimeout(() => {
  this.dataSource.paginator = this.paginator;
  this.dataSource.sort = this.sort;
});

答案 1 :(得分:0)

扩展trichetriche的答案,我不得不在subscribe

中添加那段代码
ngOnInit() {
 ...
 ...
 //myData is an Observable
 this.myData.subscribe(data => {
  setTimeout(() => {
    this.dataSource.sort = this.sort;
  });
 });
}