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

Angular使用mat-paginator实现服务端分页报undefined流错误如何解决

错误原因

  1. 核心报错触发原因:接口返回数据后,错误将列表数据data.apiData赋值给了this.dataSource.paginator属性。dataSource.paginator要求传入MatPaginator实例,传入普通数组后,Angular Material期望获取流却得到无效值,直接触发报错。正确赋值位置为this.dataSource.data。
  2. ngOnInit中this.loadCategoryList漏写调用括号,属于无效代码。
  3. 未初始化MatTableDataSource实例、未声明displayedColumns变量都会触发相关异常,重复为dataSource.paginator赋值属于多余操作。
  4. 重复订阅paginator.page事件且未做销毁逻辑,长期运行会导致内存泄漏。
  5. 首次触发分页请求时未指定初始分页参数,可能出现参数取值异常。

修正后代码

组件.ts代码

// 顶部导入依赖
import { MatTableDataSource } from '@angular/material/table';
import { Subscription } from 'rxjs';

// 组件类内部声明变量
dataSource = new MatTableDataSource<any>(); // 可将any替换为实际的分类数据类型
displayedColumns: string[] = ['sl', 'name', 'status', 'actions'];
length: number = 0;
private pageSub: Subscription;

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

ngOnInit(): void {}

ngAfterViewInit() {
  this.loadCategoryList();
}

loadCategoryList = (): void => {
  this.pageSub = this.paginator.page
    .pipe(
      startWith({ pageIndex: 0, pageSize: 5 }),
      switchMap((pageEvent) => {
        this.asyncService.start();
        return this.categoryService.getAllCategoryByPage({
          page: pageEvent.pageIndex + 1,
          pageSize: pageEvent.pageSize,
          searchString: ""
        })
      })
    )
    .subscribe({
      next: (data) => {
        this.length = data.totalRecord;
        this.dataSource.data = data.apiData;
        this.asyncService.finish();
      },
      error: () => {
        this.asyncService.finish();
      }
    })
};

ngOnDestroy() {
  this.pageSub?.unsubscribe();
}

其他代码说明

  • Service代码无逻辑问题,可正常使用。
  • HTML模板代码无需修改,确保displayedColumns变量和模板中列定义对应即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:00:00