【问题标题】:Angular 5 Material Table not getting data from serviceAngular 5 Material Table 未从服务中获取数据
【发布时间】:2017-09-27 20:36:14
【问题描述】:

我正在尝试使用带有 Material 表的 Angular (5) 简单地显示 MySQL 数据库中的数据。我编译成功的代码,出现了一个带有列名和分页按钮的表格,但是表格中没有显示任何数据。我知道 API 调用正在正确返回数据,并且我知道服务正在调用 API(我可以在浏览器的网络检查器中看到正确的数据)。浏览器显示错误

TypeError: _co.unitTypeDatabase.data is undefined
Stack trace:
View_UnitTypeComponent_0/<@ng:///AppModule/UnitTypeComponent.ngfactory.js:136:9 ...

看起来错误是指 html 代码中引用 unitTypeDatabase.data.length 的部分。如果那是未定义的,那么它将解释为什么表中也没有数据。我想不通的是 why 这是未定义的。我认为这与我创建new UnitTypeDatabase 的方式/时间/地点有关,但鉴于该服务已成功调用,我不确定从这里去哪里。这是我的代码:

unit-type.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { UnitType } from './unit-type';
import { UnitTypeService } from './unit-type.service';
import {DataSource} from '@angular/cdk/collections';
import {MdPaginator} from '@angular/material';
import {Observable} from 'rxjs/Observable';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Component({
  selector: 'app-unit-type',
  templateUrl: './unit-type.component.html',
  styleUrls: ['./unit-type.component.scss'],
  providers: [UnitTypeService]
})
export class UnitTypeComponent implements OnInit {
  public displayedColumns = ['unitTypeID', 'unitTypeName'];
  public unitTypeDatabase: UnitTypeDatabase | null;
  public dataSource: UnitTypeDataSource | null;

  @ViewChild(MdPaginator) paginator: MdPaginator;

  constructor(private unitTypeService: UnitTypeService) {}

  ngOnInit() {
      this.unitTypeDatabase = new UnitTypeDatabase(this.unitTypeService);
      this.dataSource = new UnitTypeDataSource(this.unitTypeDatabase, this.paginator);
  }
}

export class UnitTypeDataSource extends DataSource<UnitType> {
  constructor(private _unitTypeDatabase: UnitTypeDatabase, private _paginator: MdPaginator) {
      super();
    }

  connect(): Observable<UnitType[]> {
    const displayDataChanges = [
      this._unitTypeDatabase.dataChange,
      this._paginator.page
    ];

    return Observable.merge(...displayDataChanges).map(() => {
      const data = this._unitTypeDatabase.data.slice();

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

  disconnect() {}
}

export class UnitTypeDatabase {
  /** Stream that emits whenever the data has been modified. */
  public dataChange: BehaviorSubject<UnitType[]> = new BehaviorSubject<UnitType[]>([]);
  get data(): UnitType[] { return this.dataChange.value; }

  constructor(unitTypeService: UnitTypeService) {
      unitTypeService.getAllUnitTypes().subscribe(data => this.dataChange.next(data));
  }
}

unit-type.component.html

<div class="example-container mat-elevation-z8">
  <md-table #table [dataSource]="dataSource">

    <!-- ID Column -->
    <ng-container mdColumnDef="unitTypeID">
      <md-header-cell *mdHeaderCellDef> ID </md-header-cell>
      <md-cell *mdCellDef="let row"> {{row.unitTypeID}} </md-cell>
    </ng-container>

    <!-- Name Column -->
    <ng-container mdColumnDef="unitTypeName">
      <md-header-cell *mdHeaderCellDef> Name </md-header-cell>
      <md-cell *mdCellDef="let row"> {{row.unitTypeName}} </md-cell>
    </ng-container>

    <md-header-row *mdHeaderRowDef="displayedColumns"></md-header-row>
    <md-row *mdRowDef="let row; columns: displayedColumns;"></md-row>
  </md-table>

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

unit-type.ts

export class UnitType {
    constructor(
        public unitTypeID: number,
        public unitTypeName: string
    ){}
}

unit-type.service.ts

import { Injectable } from '@angular/core';
import { UnitType } from './unit-type';
import { Headers, Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class UnitTypeService {
  private unit_types_Url = 'api/unit-types';  // URL to web api
  private headers = new Headers({'Content-Type': 'application/json'});

  constructor(private http: Http) { }

  getAllUnitTypes(): Observable<UnitType[]> {
    return this.http.get(this.unit_types_Url)
           .map(response => response.json().data as UnitType[]);
  }
}

我从 Material 网站的示例开始,但它没有使用服务检索数据。我还尝试匹配来自How to use md-table with services in Angular 4 的问题和答案,但我一定遗漏了一些东西。希望这是一个明显而简单的错误或误解,有人可以快速发现。谢谢!

编辑 完整的堆栈跟踪是:

ERROR TypeError: _this._unitTypeDatabase.data is undefined
Stack trace:
[208]/UnitTypeDataSource.prototype.connect/<@http://localhost:4200/main.bundle.js:93:17
MapSubscriber.prototype._next@http://localhost:4200/vendor.bundle.js:51417:22
Subscriber.prototype.next@http://localhost:4200/vendor.bundle.js:37214:13
OuterSubscriber.prototype.notifyNext@http://localhost:4200/vendor.bundle.js:48573:9
InnerSubscriber.prototype._next@http://localhost:4200/vendor.bundle.js:117362:9
Subscriber.prototype.next@http://localhost:4200/vendor.bundle.js:37214:13
Subject.prototype.next@http://localhost:4200/vendor.bundle.js:26457:17
BehaviorSubject.prototype.next@http://localhost:4200/vendor.bundle.js:49978:9
UnitTypeDatabase/<@http://localhost:4200/main.bundle.js:122:78
SafeSubscriber.prototype.__tryOrUnsub@http://localhost:4200/vendor.bundle.js:37363:13
SafeSubscriber.prototype.next@http://localhost:4200/vendor.bundle.js:37310:17
Subscriber.prototype._next@http://localhost:4200/vendor.bundle.js:37250:9
Subscriber.prototype.next@http://localhost:4200/vendor.bundle.js:37214:13
MapSubscriber.prototype._next@http://localhost:4200/vendor.bundle.js:51423:9
Subscriber.prototype.next@http://localhost:4200/vendor.bundle.js:37214:13
onLoad@http://localhost:4200/vendor.bundle.js:53409:21
ZoneDelegate.prototype.invokeTask@http://localhost:4200/polyfills.bundle.js:6443:17
onInvokeTask@http://localhost:4200/vendor.bundle.js:4914:24
ZoneDelegate.prototype.invokeTask@http://localhost:4200/polyfills.bundle.js:6442:17
Zone.prototype.runTask@http://localhost:4200/polyfills.bundle.js:6242:28
ZoneTask/this.invoke@http://localhost:4200/polyfills.bundle.js:6496:28

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    尝试在模板中使用 elvis 运算符 ? 开始。如果只是模板问题,那应该可以解决您的问题。

    [length]="unitTypeDatabase?.data?.length"
    

    原因是当视图被渲染时,还没有定义unitTypeDatabase,因为它只是在ngOnInit() 中初始化。看看这是否解决了你的问题。

    【讨论】:

    • 感谢您的提示,但不幸的是,这并没有解决问题。我仍然在浏览器中遇到与以前相同的错误。
    【解决方案2】:

    问题出在 unit-type.service.ts 中。应该是:

    getAllUnitTypes(): Observable<UnitType[]> {
        return this.http.get(this.unit_types_Url)
               .map(response => response.json() as UnitType[]);
    }
    

    我错过了一个事实,即返回的 JSON 中没有数据对象,因此一旦删除,所有信息都可见并正确显示在表中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 2020-09-08
      相关资源
      最近更新 更多