0

I an using Angular 9 and trying to implement the pagination. I am getting the below error:

ERROR TypeError: Cannot read property 'slice' of undefined

My component code:

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { MatPaginator, PageEvent } from '@angular/material/paginator';
    import { MatTableDataSource } from '@angular/material/table';
    
    import { TestResult } from '../models/testResult';
    import { TestResultService } from '../test-result/test-result.service';
    
    @Component({
      selector: 'app-test-result-list',
      templateUrl: './test-result-list.component.html'
    })
    
    export class TestResultListComponent implements OnInit {
    
      testResults: TestResult[];
      dataSource: MatTableDataSource<TestResult>;
      displayColumns = ["tagNo", "testStart", "unitTestId", "isApproved", "valveTestEnvironment"];
    
      length = 100;
      pageSize = 10;
      pageSizeOptions = [1, 2, 5, 10];
    
      @ViewChild(MatPaginator) paginator: MatPaginator;
      pageEvent: PageEvent;
    
    constructor(private readonly testResultService: TestResultService) { }
    
      loadData(pageIndex, pageSize)
      {
        this.dataSource = new MatTableDataSource<TestResult>(this.testResults.slice(pageIndex, pageIndex + pageSize));
      }
    
      ngOnInit(): void {
        this.testResultService.getTestResults().subscribe(result => this.testResults = result);
        this.loadData(0, this.pageSize);
      }
    }

I have used lice with this.testResults which is already defined as Array of TestResult Type.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
user1126122
  • 59
  • 2
  • 5

1 Answers1

1

testResults variable is assigned asynchronously. By the time loadData() funciton is called, testResults isn't assigned any values yet. All statements directly depending on it should be async as well i.e, they should be inside the subscription callbacks.

ngOnInit(): void {
  this.testResultService.getTestResults().subscribe(result => {
    this.testResults = result;
    this.loadData(0, this.pageSize);     // <-- inside subscription
  });
}

You could learn more about async data here.

ruth
  • 29,535
  • 4
  • 30
  • 57