首页 > 解决方案 > 使用@angular/material 时未定义的属性长度

问题描述

我正在使用材料创建数据表。数据来自 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>

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

谢谢,迈克尔

标签: angularangular-material

解决方案


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

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

在 tagService 返回响应之前。为了修复它,您需要在this.service.getTags().subscribe(<put assignment here>)方法内部进行上述分配。

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


推荐阅读