Mat-paginator无法在mat-table

时间:2020-10-28 20:30:29

标签: angular .net-core dynamic-data mat-table batching

我正在批量将数据加载到我的mat-table中。该API可以正常工作并显示数据,但是当我单击mat-paginator的下一个按钮时,它将显示下一批100,然后禁用所有导航按钮。 Image showing mat-paginator

在mat-pagonator中,我添加了pageEvent并在.ts文件中定义了它的功能。

.html文件上的分页器

 <mat-paginator #paginator
                 [length] ="totalRecords"
                 [pageSize]="100"
                 (page)="pageEvent = $event; changePage($event)" showFirstLastButtons>
  </mat-paginator>

这里,getIntegrationErrors是将数据与数据源绑定的函数。但是由于页面更改事件使调用不在该功能内进行,因此我不得不在changePage函数中再次绑定数据。 .ts文件

import { Component, OnInit, ViewChild, AfterViewInit, Inject } from '@angular/core';
import { FormControl, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RepositoryService } from '../shared/services/repository.service';
import { Integration } from '../_interfaces/integration.model';
import { MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { IntegrationWrapper } from '../_interfaces/integrationWrapper.model';
import { PageEvent } from '@angular/material/paginator';
import { TranslateService, TranslateParser } from '@ngx-translate/core';
import { map } from 'jquery';
import { tap } from 'rxjs/operators';
//import { MyMatPaginatorIntl } from '../paginator/MyMatPaginatorIntl';

@Component({
  selector: 'app-integration',
  templateUrl: './integration.component.html',
  styleUrls: ['./integration.component.css'],
  animations: [
    trigger('detailExpand', [
      state('collapsed', style({ height: '0px', minHeight: '0', display: 'none' })),
      state('expanded', style({ height: '*' })),
      transition('expanded => collapsed', [animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')]),
      transition('collapsed => expanded', [animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')])
    ]),
  ],
})
export class IntegrationComponent implements OnInit {

  public integrate: Integration[];
  public integrate2: IntegrationWrapper;
  public displayedColumns = ['EntityType', 'SourceID', 'FieldName', 'ExceptionSource', 'Message', 'IsResolved', 'Modified'];
  public dataSource = new MatTableDataSource<Integration>();
  public expandedElement: ['EntityType: String', 'SourceID: string', 'FieldName: string', 'ExceptionSource: string', 'Message: string', 'IsResolved: boolean', 'Modified: date'];
  public isChecked: boolean;

  public Value: string;
  public isLoading = true;
  public totalRecords: number;
  public batchSize = 100;
  public pageNum = 1;

  public pageSlice;
  //public dataSource;
  @ViewChild(MatSort, { static: true }) sort: MatSort;
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  pageEvent;

  control: FormControl = new FormControl('', [
    Validators.required,
    Validators.maxLength(30)
  ]);

  constructor(private repoService: RepositoryService) { }

  ngOnInit() {

    this.getIntegrationErrors("false");

    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;


    this.dataSource.filterPredicate =
      (data: Integration, filtersJson: string) => {
        const matchFilter = [];
        const filters = JSON.parse(filtersJson);

        filters.forEach(filter => {
          const val = data[filter.id] === null ? '' : data[filter.id];
          matchFilter.push(val.toLowerCase().includes(filter.value.toLowerCase()));
        });
        return matchFilter.every(Boolean);
      };

  }


  changePage(event: any) {

    console.log(event);
    this.isLoading = true;
    const startIndex = event.pageIndex + event.pageSize;
    let endIndex = startIndex + event.pageSize;

    this.paginator._intl.getRangeLabel = (page: number, pageSize: number, length: number) => {
      const start = event.pageIndex + event.pageSize;
      const end = (startIndex + event.pageSize) > this.integrate2.TotalCount ? this.integrate2.TotalCount : (startIndex + event.pageSize);
      return `${start} - ${end} of ${this.integrate2.TotalCount}`;
    };

    if (endIndex > this.integrate2.TotalCount) {
      endIndex = this.integrate2.TotalCount;
    }
    this.pageNum += 1;
    let apiAddress: string = "api/integrations/" + "false" + "/" + this.pageNum + "/" + this.batchSize;
    alert(apiAddress);
    
    this.repoService.getData(apiAddress).subscribe(i => {
      console.log(i);
      this.isLoading = false;
      this.integrate2 = i as IntegrationWrapper;
      this.dataSource.data = this.integrate2.IntegrationLogsBatch;
      this.totalRecords = this.integrate2.TotalCount;
    },
      error => this.isLoading = false
    );
    this.pageSlice = this.integrate2.IntegrationLogsBatch.slice(startIndex, endIndex);
  }

  applyFilter(filterValue: string) {
    const tableFilters = [];
    tableFilters.push({
      id: 'SourceID',
      value: filterValue
    });

    this.dataSource.filter = JSON.stringify(tableFilters);
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  clearFilters() {
    this.dataSource.filter = '';
    this.Value = '';
  }

  checkValue(isChecked) {
    if (isChecked)
      this.getIntegrationErrors("true");
    else
      this.getIntegrationErrors("false");
  }

  public getIntegrationErrors(v: string) {
   
    let apiAddress: string = "api/integrations/" + v + "/" + this.pageNum + "/" + this.batchSize;
    alert(apiAddress);
    this.repoService.getData(apiAddress).subscribe(i => {
      console.log(i);
      this.isLoading = false;
      this.integrate2 = i as IntegrationWrapper;
      this.dataSource.data = this.integrate2.IntegrationLogsBatch;
      this.totalRecords = this.integrate2.TotalCount;
    },
      error => this.isLoading = false
    );
  }

}

这是我定义服务功能以获取数据的文件。

service.ts文件

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { EnvironmentUrlService } from './environment-url.service';

@Injectable()
export class RepositoryService {

    constructor(private http: HttpClient, private envUrl: EnvironmentUrlService) { }

  public getData(route: string) {
      return this.http.get(this.createCompleteRoute(route, this.envUrl.APIRoot));
    }

  public create(route: string, body) {
      return this.http.post(this.createCompleteRoute(route, this.envUrl.APIRoot), body, this.generateHeaders());
    }

  public update(route: string, body) {
      return this.http.put(this.createCompleteRoute(route, this.envUrl.APIRoot), body, this.generateHeaders());
    }

  public delete(route: string) {
      return this.http.delete(this.createCompleteRoute(route, this.envUrl.APIRoot));
    }

    private createCompleteRoute(route: string, envAddress: string) {
        return `${envAddress}/${route}`;
    }
}

0 个答案:

没有答案
相关问题