【发布时间】:2018-11-19 22:15:27
【问题描述】:
我正在使用材料来创建数据表。数据来自 REST 服务,并且在获取时没有任何错误。浏览器还在数据表中正确显示数据。但是,我的数据数组的属性长度可能是未定义的,这会导致以下错误:
错误类型错误:无法读取未定义的属性“长度” 在 TagListDataSource.push../src/app/tag/tag-list-datasource.ts.TagListDataSource.connect (tag-list-datasource.ts:39)
这里是datasource.ts文件:
import { DataSource } from '@angular/cdk/collections';
import { MatPaginator, MatSort } from '@angular/material';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';
import {Tag} from './tag';
import {TagService} from './tag.service';
/**
* Data source for the TagList view. This class should
* encapsulate all logic for fetching and manipulating the displayed data
* (including sorting, pagination, and filtering).
*/
export class TagListDataSource extends DataSource<Tag> {
private tags: Tag[];
constructor(private paginator: MatPaginator, private sort: MatSort, private service: TagService) {
super();
}
/**
* Connect this data source to the table. The table will only update when
* the returned stream emits new items.
* @returns A stream of the items to be rendered.
*/
connect(): Observable<Tag[]> {
this.service.getTags().subscribe(data => this.tags = data);
// Combine everything that affects the rendered data into one update
// stream for the data-table to consume.
const dataMutations = [
observableOf(this.tags),
this.paginator.page,
this.sort.sortChange
];
// Set the paginator's length
this.paginator.length = this.tags.length;
return merge(...dataMutations).pipe(map(() => {
return this.getPagedData(this.getSortedData([...this.tags]));
}));
}
/**
* Called when the table is being destroyed. Use this function, to clean up
* any open connections or free any held resources that were set up during connect.
*/
disconnect() {}
/**
* Paginate the data (client-side). If you're using server-side pagination,
* this would be replaced by requesting the appropriate data from the server.
*/
private getPagedData(data: Tag[]) {
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
}
/**
* Sort the data (client-side). If you're using server-side sorting,
* this would be replaced by requesting the appropriate data from the server.
*/
private getSortedData(data: Tag[]) {
if (!this.sort.active || this.sort.direction === '') {
return data;
}
return data.sort((a, b) => {
const isAsc = this.sort.direction === 'asc';
switch (this.sort.active) {
case 'name': return compare(a.name, b.name, isAsc);
case 'id': return compare(+a.id, +b.id, isAsc);
default: return 0;
}
});
}
}
/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a, b, isAsc) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
这是component.ts文件
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatSort } from '@angular/material';
import { TagListDataSource } from './tag-list-datasource';
import {TagService} from './tag.service';
@Component({
selector: 'app-tag-list',
templateUrl: './tag-list.component.html',
styleUrls: ['./tag-list.component.css'],
})
export class TagListComponent implements OnInit {
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
dataSource: TagListDataSource;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['id', 'name'];
constructor(private service: TagService) { }
ngOnInit() {
this.dataSource = new TagListDataSource(this.paginator, this.sort, this.service);
}
}
这是component.html文件:
<div class="mat-elevation-z8">
<table mat-table class="full-width-table" [dataSource]="dataSource" matSort aria-label="Elements">
<!-- Id Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
<td mat-cell *matCellDef="let row">{{row.id}}</td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
<td mat-cell *matCellDef="let row">{{row.name}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator #paginator
[length]="dataSource.tags?.length"
[pageIndex]="0"
[pageSize]="50"
[pageSizeOptions]="[25, 50, 100, 250]">
</mat-paginator>
</div>
数组 tags 未初始化,因此第 39 行 (this.paginator.length = this.tags.length;) 会产生此错误。因此,我尝试通过 private tags: Tag[] = Array(); 来初始化 tags,这会导致一个空数据表(因为标签被初始化为一个空数组)。如何初始化数组 tags 以避免上述错误,然后用我的 REST 服务中的数据填充数组?
谢谢, 迈克尔
【问题讨论】:
-
你还没有分享你的 HTML,也许添加一个 *ngIf 来检查数据是否未定义 - 这将进入你的 HTML 区域
-
感谢 AlqbalRaj!我现在分享了我的 html 文件。因为错误是在 datasource.ts 文件中产生的,所以我看不到 *ngIf 指令如何解决问题。
-
你真的需要自己的数据源实现吗? Mayby 查看link 的常用用法。您可以订阅您的数据服务并提供 MatTableDataSource 内置类。
-
谢谢沃尔特!你是绝对正确的,我真的不需要我自己的数据源。它与 MatTableDataSource 完美配合。
-
很高兴它有效。你能标记我的答案吗?