Angular4: ERROR TypeError: Cannot read property 'length' of undefined while accessing length property

时间:2017-11-13 06:27:09

标签: angular pagination angular-material

i'am working on a assignment of angular 4, i'am new to it, i'am applying pagination for mat-table,getting some problem in it, while i'am printing data to console it is displaying as below enter image description here

while i'am trying to apply dataSource.data.length, getting below error.

WellComponent.html:57 ERROR TypeError: Cannot read property 'length' of undefined
    at Object.View_WellComponent_0._co [as updateDirectives] (WellComponent.html:60)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13075)
    at checkAndUpdateView (core.es5.js:12255)
    at callViewAction (core.es5.js:12620)
    at execComponentViewsAction (core.es5.js:12552)
    at checkAndUpdateView (core.es5.js:12261)
    at callViewAction (core.es5.js:12620)
    at execEmbeddedViewsAction (core.es5.js:12578)
    at checkAndUpdateView (core.es5.js:12256)
    at callViewAction (core.es5.js:12620)

Can i get help in this aspect, how should i access that length property.

Component:

    import { MatPaginator } from '@angular/material';
    import { DataSource } from '@angular/cdk/collections';
    import { Component, OnInit,ViewChild,ChangeDetectorRef } from '@angular/core';
    import { WellService } from '../services/well.service';
    import { Well } from '../well/well';
    import {  Observable  } from 'rxjs/Rx';
    import { BehaviorSubject } from  'rxjs/BehaviorSubject';
    import 'rxjs/add/operator/startWith';
    import 'rxjs/add/observable/merge';
    import 'rxjs/add/operator/map';



    @Component({
      selector: 'app-well',
      templateUrl: './well.component.html',
      styleUrls: ['./well.component.css'],
      providers:[WellService]
    })



    export class WellComponent implements OnInit {
      title = 'Wells';
      header:string;  
      displayedColumns = ['active', 'company', 'country', 'well','wellbore'];
      public dataSource: WellDataSource | any;
      obs:any;

      @ViewChild(MatPaginator) paginator : MatPaginator;

      constructor(private wellService:WellService) {

        this.header='assets/images/BHI_header_logo_bd.png'  

       }

       ngOnInit() {
        this.obs = this.wellService.getWells();
        this.dataSource = new WellDataSource(this.obs, this.paginator);

      }

      }

      export class WellDataSource extends DataSource<any> {

      constructor(private _obs: any, private _paginator: MatPaginator) {
        super();
      }

      connect(): Observable<any[]> {
        const displayDataChanges = [
          this._obs,
          this._paginator.page,
        ];

        return this._obs.flatMap(x => {
          return Observable.merge(...displayDataChanges).map(() => {
            const data = x.slice();
            console.log(data);
            const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
            console.log(startIndex);
            console.log(this._paginator.pageSize)
            console.log(this._obs);
            console.log(x.slice());
            return data.splice(startIndex, this._paginator.pageSize);
          });
        })
      }

        disconnect() {}
      }


**HTML:**

<div>
  <div class="image"><img  [src]="header" ></div>

  <div class="w3-display-left">
  <nav>
     <li><a routerLink="/wells" routerLinkActive="active">My Wells</a></li>
      <li><a routerLink="/dev" routerLinkActive="active">Well Management</a></li>
      <li><a routerLink="/dev" routerLinkActive="active">Admin Tools</a></li>
  </nav>
  <div class="w3-display-right">
    <button mat-button>Reset</button>
    <button mat-button>Refresh</button>
    <button mat-button>View Wireline</button>
    <button mat-button>Chat</button>
    <button mat-button>View Seismic</button>
    <button mat-button>Alerts</button>

  </div>


  <br>
  <br>
   <div> 
        <mat-table #table [dataSource]="dataSource">
    <!-- Active -->
    <ng-container matColumnDef="active">
      <mat-header-cell *matHeaderCellDef> Active </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.active}} </mat-cell>
    </ng-container>

    <!-- Company -->
    <ng-container matColumnDef="company">
      <mat-header-cell *matHeaderCellDef> Company </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.company}} </mat-cell>
    </ng-container>

    <!-- Country -->
    <ng-container matColumnDef="country">
      <mat-header-cell *matHeaderCellDef>Country</mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.country}} </mat-cell>
    </ng-container>

    <!-- Well -->
    <ng-container matColumnDef="well">
      <mat-header-cell *matHeaderCellDef> Well </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.well}} </mat-cell>
    </ng-container>


        <!-- Wellbore -->
        <ng-container matColumnDef="wellbore">
          <mat-header-cell *matHeaderCellDef> Wellbore </mat-header-cell>
          <mat-cell *matCellDef="let row"> {{row.wellbore}} </mat-cell>
        </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
  <mat-paginator #paginator
  [length]="dataSource.data.length"
  [pageIndex]="0"
  [pageSize]="25"
  [pageSizeOptions]="[5, 10, 25, 100]">
</mat-paginator>
</div>
</div> 
<div>    
    <router-outlet></router-outlet>
    </div>

3 个答案:

答案 0 :(得分:5)

The error is because of you are trying to access data before it available

Try to use safe operator :

dataSource.data?.length

OR

make some initialisation inside constructor

dataSource.data = [];

As per your code change [length]="dataSource.data.length" to [length]="obs.data?.length" , like this :

<mat-paginator #paginator
  [length]="obs.data?.length"
  [pageIndex]="0"
  [pageSize]="25"
  [pageSizeOptions]="[5, 10, 25, 100]">
</mat-paginator>

答案 1 :(得分:0)

初始化数组会导致错误消失,但是表中的数据将永远不会更新-它为空。添加问号(即dataSource.data?.length)无法正常工作,因为在其他地方还没有希望它未定义。

有些孩子叫我尝试一个BehaviorSubject。它们是始终具有价值的Observable。当您订阅时,您可以获得最新的价值。他们也是观察者,您可以告诉他们下一个值是什么。在这里阅读更多。

http://reactivex.io/rxjs/manual/overview.html#behaviorsubject

我将dataSource.data设置为BehaviorSubject,这是孩子告诉我的方式,初始值[]然后在值更改时(通过next())告诉了它。

而且,因为我正在进行排序和分页,所以我不得不更新该代码以使用this.data.getValue()而不是this.data。

答案 2 :(得分:0)

我通过两种方法解决了这个问题:

a)安全操作员

  

[length] =“ dataSource.data?.length”

b)正确初始化数据源(避免切片错误)

ngOnInit() {
  this.dataSource = new EmplTblDataSource(this.paginator, this.sort);
  this.dataSource.data=[];
}

然后,我用OnChanges方法更新表内容