浏览器报错:Cannot read properties of undefined (reading 'pageIndex')

1,670 阅读1分钟

今天又碰到一个以前遇到过的问题,当初偷懒没有记录,在这里记录一下。 页面为Angular-Material带有分页器的表格

浏览器报错

ERROR TypeError: Cannot read properties of undefined (reading 'pageIndex')
    at SupplierOrderWarehouseComponent.fetchTableInfo (supplier-order-warehouse.component.ts:73:66)
    at SupplierOrderWarehouseComponent.ngOnInit (supplier-order-warehouse.component.ts:46:10)
    at checkAndUpdateDirectiveInline (core.js:24274:1)
    at checkAndUpdateNodeInline (core.js:31398:1)
    at checkAndUpdateNode (core.js:31360:1)
    at debugCheckAndUpdateNode (core.js:31987:1)
    at debugCheckDirectivesFn (core.js:31951:1)
    at Object.updateDirectives (supplier-order-warehouse.component.html:132:25)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:31947:1)
    at checkAndUpdateView (core.js:31342:1)

其出错的来源其实就在于,我是这么调用数据的:

ngOnInit(): void {
    this.confSvc.operateAuth('采购收货查询');
    this.fetchTableInfo();
    merge(this.paginator.page).subscribe(() => {
      this.fetchTableInfo();
    });
    this.isLoading = false;
  }
  
// 更新表格:
fetchTableInfo(): void {
    ……
    this.purchaseService.getSupplierWarehouseList(this.paginator.pageIndex, searchParamsStr).subscribe(
      res => {
      ……
  }

分页器代码是这样的:

<mat-paginator [hidePageSize]="true" [length]="tableDataLength"
    [pageIndex]="pageIndexStart"[pageSize]="pageSize" showFirstLastButtons>
</mat-paginator>

所以页面加载的时候,第一步先调用了API接口,而接口传参需要this.paginator.pageIndex,而html还未获取到分页器的paginator属性,所以读取不到pageIndex

解决办法

改变调用的生命周期即可

ngOnInit(): void {
}
ngAfterViewInit(): void {
    this.confSvc.operateAuth('采购收货查询');
    this.fetchTableInfo();
    merge(this.paginator.page).subscribe(() => {
        this.fetchTableInfo();
    });
    this.isLoading = false;
  }

生命周期真的很重要啊,一定要好好学习掌握这一块儿