You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material服务端分页异常问题求助

Angular Material服务端分页异常问题解决

环境版本

"@angular/cli": "~8.0.6",
"@angular/compiler-cli": "~8.0.3",
"@angular/language-service": "~8.0.3"
"@angular/material": "^8.2.3"

问题现象

总数据量为29条,首次加载且每页条数设为10时,分页器显示“1-10 of 29”,显示正常。但点击下一页按钮后,分页器显示“1-10 of 10”,且下一页、最后一页按钮被禁用,预期应显示“11-20 of 29”。

代码片段

HTML部分

<mat-paginator style="width: 100%" [length]="length" [pageIndex]="pageIndex" [pageSize]="pageSize"
[pageSizeOptions]="pageSizeOptions" showFirstLastButtons (page)="pageChanged($event)"></mat-paginator>

组件代码

export class myComponent implements OnInit,AfterViewInit {

  @ViewChild(MatPaginator, {static: false}) 
  paginator: MatPaginator;

  public displayedColumns: string[] = ['code', 'name', 'id', 
                                        'close', 'avg5p', 'avg20p', 'avg60p',
                                        'avg5q', 'avg20q', 'avg60q',
                                        'actions'];
  public dataSource = new MatTableDataSource();
  public type: string;
  public last_updated: string;

  length = 0;
  pageIndex = 0;
  pageSize = 10;
  pageSizeOptions = [ 10, 20 ];

  constructor(private sessionService: SessionService,private http: HttpClient,private dialog: MatDialog, private snackBar: MatSnackBar) {
    this.type = "1";
    this.dataSource.data = [];
    this.dataSource.filteredData = [];
  }

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.getData();
  }

  getData() {
    let query = {};
    if (this.sessionService.token) {
      query['token'] = this.sessionService.token;
    }
    query['type'] = this.type;
    query['page_no'] = this.pageIndex;
    query['page_rows'] = this.pageSize;
    this.http.post(environment.api_url + "/api/myquery", query).subscribe((results:any) => {
      if ( results.api_code == 0 ) {
        this.last_updated = results.updated
        this.dataSource.data = results.data;
        this.length = results.totalRecords;
      } else {
        this.snackBar.open(this.sessionService.getMessage("SESSION_INVALID"), "", {
          duration: 3000
        });
        this.sessionService.logout();
      }
    });
  }

  pageChanged(event: PageEvent) {
    this.pageIndex = event.pageIndex;
    this.pageSize = event.pageSize;
    this.getData();
  }

}

解决方案(来自@Eliseo的评论)

问题根源是同时启用了MatTable内置分页逻辑和手动绑定分页器属性,导致两者冲突:

  1. 移除自动分页绑定:删除ngAfterViewInit中的this.dataSource.paginator = this.paginator;代码。服务端分页场景下,无需让MatTable自动处理分页,完全由组件控制分页参数和数据即可。
  2. 校验分页参数匹配:确认后端分页规则与前端pageIndex是否一致。Angular Material的pageIndex从0开始,如果后端分页页码从1开始,需在请求时将pageIndex + 1作为page_no传入,避免请求错误页码导致数据异常。
  3. 确保总条数正确返回:每次请求分页数据时,后端必须正确返回totalRecords总条数,且前端要准确赋值给this.length,保证分页器能正确计算总页数。

内容的提问来源于stack exchange,提问作者Vincent Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 04:35:45