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

