Angular 4材料无法获取表中的数据

时间:2017-11-03 06:59:12

标签: angular service material

我是Angular的新手,我的目标是点击服务并填充表格中的数据,我已经通过使用我获得的链接实现了,但没有运气得到以下错误,任何人都可以帮助我吗?

ERROR TypeError: Cannot read property 'data' of undefined
    at Object.View_WellComponent_0._co [as updateDirectives] (WellComponent.html:46)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13093)
    at checkAndUpdateView (core.es5.js:12270)
    at callViewAction (core.es5.js:12638)
    at execComponentViewsAction (core.es5.js:12570)
    at checkAndUpdateView (core.es5.js:12276)
    at callViewAction (core.es5.js:12638)
    at execEmbeddedViewsAction (core.es5.js:12596)
    at checkAndUpdateView (core.es5.js:12271)
    at callViewAction (core.es5.js:12638)
View_WellComponent_0 @ WellComponent.html:41
proxyClass @ compiler.es5.js:14971
webpackJsonp.../../../core/@angular/core.es5.js.DebugContext_.logError @ core.es5.js:13433
webpackJsonp.../../../core/@angular/core.es5.js.ErrorHandler.handleError @ core.es5.js:1080
(anonymous) @ core.es5.js:4819
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:392
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.run @ zone.js:142
webpackJsonp.../../../core/@angular/core.es5.js.NgZone.runOutsideAngular @ core.es5.js:3844
webpackJsonp.../../../core/@angular/core.es5.js.ApplicationRef_.tick @ core.es5.js:4819
(anonymous) @ core.es5.js:4684
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:392
onInvoke @ core.es5.js:3890
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.run @ zone.js:142
webpackJsonp.../../../core/@angular/core.es5.js.NgZone.run @ core.es5.js:3821
next @ core.es5.js:4684
schedulerFn @ core.es5.js:3635
webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.next @ Subscriber.js:185
webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber._next @ Subscriber.js:125
webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next @ Subscriber.js:89
webpackJsonp.../../../../rxjs/Subject.js.Subject.next @ Subject.js:55
webpackJsonp.../../../core/@angular/core.es5.js.EventEmitter.emit @ core.es5.js:3621
checkStable @ core.es5.js:3855
onHasTask @ core.es5.js:3903
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.hasTask @ zone.js:445
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate._updateTaskCount @ zone.js:465
webpackJsonp.../../../../zone.js/dist/zone.js.Zone._updateTaskCount @ zone.js:289
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask @ zone.js:209
drainMicroTaskQueue @ zone.js:602
Promise resolved (async)
scheduleMicroTask @ zone.js:585
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:414
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:236
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:256
scheduleResolveOrReject @ zone.js:842
ZoneAwarePromise.then @ zone.js:932
webpackJsonp.../../../core/@angular/core.es5.js.PlatformRef_._bootstrapModuleWithZone @ core.es5.js:4537
webpackJsonp.../../../core/@angular/core.es5.js.PlatformRef_.bootstrapModule @ core.es5.js:4522
../../../../../src/main.ts @ main.ts:12
__webpack_require__ @ bootstrap 5ae4122d006709605fc5:54
0 @ main.ts:12
__webpack_require__ @ bootstrap 5ae4122d006709605fc5:54
webpackJsonpCallback @ bootstrap 5ae4122d006709605fc5:25
(anonymous) @ main.bundle.js:1

HTML是: 的 Wellcomponent.html:

<div style="text-align:center">  
  <div><img width="1100" [src]="header" margin-top:-40px></div>
   <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.well.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.well.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.well.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]="wellDatabase.data.length"
  [pageIndex]="0"
  [pageSize]="25"
  [pageSizeOptions]="[5, 10, 25, 100]">
</mat-paginator>


      </div>           

该组件是: WellComponent:

import { MatPaginator } from '@angular/material';
import { DataSource } from '@angular/cdk/collections';
import { Component, OnInit,ViewChild } 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'];
  wellDatabase :  WellDatabase | any;
  dataSource: WellDataSource | any;

  @ViewChild(MatPaginator) paginator : MatPaginator;

  constructor(private wellService:WellService) {

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

   }

  ngOnInit() {
    this.dataSource = new WellDataSource(this.wellDatabase,this.paginator);
    console.log(this.dataSource);
  }

}
export class WellDatabase implements OnInit {

  public dataChange: BehaviorSubject<Well[]> = new BehaviorSubject<Well[]>([]);
  get data(): Well[] { return this.dataChange.value }

  constructor(wellService: WellService) {
    wellService.getWells().subscribe(data => this.dataChange.next(data));
  }



  ngOnInit() {


  }

}
export class WellDataSource extends DataSource<any> {

  constructor(private _wellDatabase : WellService, private _paginator: MatPaginator){
    super();
  }

  connect(): Observable<Well[]> {

const displayDataChanges = [
      this._wellDatabase.getWells(),
      this._paginator.page
    ];
    return Observable.merge(...displayDataChanges).map((data, page) => {
      const clonedData = data.slice();
      console.log(data);

      const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
      return data.splice(startIndex, this._paginator.pageSize);
    })
  }

  disconnect() {}
}  

服务是: WellService:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response  } from '@angular/http';
import { Observable,Subject } from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';  
import { Well } from '../well/well';
import 'rxjs/Rx';
@Injectable()
export class WellService {


  constructor(private  http:Http) { }
public getWells(): Observable < Well[] > {  
    return this.http.get('http://localhost:8080/RESTfulExample/rest/auth/testuser1/pass',{headers:this.getHeaders()}).map((response: Response) => {  
        return <Well[] > response.json().wellList;  
    }).catch(this.handleError);  
}  
//    
private handleError(errorResponse: Response) {  
    console.log(errorResponse.statusText);  
    return Observable.throw(errorResponse.json().error || "Server error");  
}  
private getHeaders(){
    // I included these headers because otherwise FireFox
    // will request text/html instead of application/json
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    return headers;
  }

}

请帮助我解决这个问题,我知道我犯的是小错误,但我无法确定Angular中的知识非常低,根据我的观点,我试图调用的其他服务方法没有被调用。

1 个答案:

答案 0 :(得分:0)

您的wellDatabase是一个不包含数据的类。这就是抛出未定义异常的原因。

请参阅下面的解决方案代码。

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

更改为

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