使用@ angular / material

时间:2018-11-19 12:43:26

标签: angular angular-material

我正在使用材料创建数据表。数据来自REST服务,并且被提取而没有任何错误。浏览器还会在数据表中正确显示数据。但是,我的数据数组的属性长度可以不确定,从而导致以下错误:

错误TypeError:无法读取未定义的属性“ length”     在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>

数组标签未初始化,因此第39行( this.paginator.length = this.tags.length; )可能产生此错误。因此,我尝试通过私有标签初始化标签:Tag [] = Array(); 导致数据表为空(因为标签被初始化为空数组)。如何初始化数组标签以避免上述错误,然后用我的REST服务中的数据填充数组?

谢谢, 迈克尔

1 个答案:

答案 0 :(得分:0)

发生错误是因为您读取了标签的长度:

this.paginator.length = this.tags.length;

在tagService返回响应之前。为了解决这个问题,您需要在this.service.getTags().subscribe(<put assignment here>)方法内进行上述分配。

正如我也在评论中写道,建议您使用内置MatTableDataSource类。