使用角垫表时,在控制台上观察到错误

时间:2018-09-16 09:44:56

标签: angular typescript angular-material

我正在使用角和角材料来创建mat table。 一切正常。只是我在控制台中看到一个错误,无法解决该错误。再次,我看到我的数据已加载,分页有效,但是我确实在控制台上看到了我不想要的错误。我该如何纠正。

控制台错误: enter image description here

MessageDataTableDataData.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 { MessageData } from '../../data-model/MessageData';

export class MessageDataTableDataSource extends DataSource<MessageData> {

  constructor(private paginator: MatPaginator, 
    private sort: MatSort, private data: MessageData[]) {
      super();
  }

  connect(): Observable<MessageData[]> {
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    this.paginator.length = this.data.length;

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  disconnect() {}

  private getPagedData(data: MessageData[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  private getSortedData(data: MessageData[]) {
    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 'id': return compare(+a.Message.Id, +b.Message.Id, isAsc);
        default: return 0;
      }
    });
  }
}

function compare(a, b, isAsc) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

HTML模板

<div class="mat-elevation-z8">
    <table mat-table #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.message.id}}</td>
        </ng-container>

        <!-- Message Text Column -->
        <ng-container matColumnDef="messageText">
            <th mat-header-cell *matHeaderCellDef mat-header>Message Text</th>
            <td mat-cell *matCellDef="let row">{{row.message.messageText}}</td>
        </ng-container>

        <!-- Delivery Date -->
        <ng-container matColumnDef="deliveryDate">
            <th mat-header-cell *matHeaderCellDef mat-header>Delivery Date</th>
            <td mat-cell *matCellDef="let row">{{row.message.deliveryDateTime}}</td>
        </ng-container>

        <!-- Status Column -->
        <ng-container matColumnDef="status">
            <th mat-header-cell *matHeaderCellDef mat-header>Status</th>
            <td mat-cell *matCellDef="let row">{{row.message.messageStatus}}</td>
        </ng-container>

        <!-- Action Column -->
        <ng-container matColumnDef="action">
            <th mat-header-cell *matHeaderCellDef mat-header>Action</th>
            <td mat-cell *matCellDef="let row">
                <button type="button" class="btn btn-danger"
                [disabled]="row.message.messageStatus != 'PENDING'" 
                (click)="cancelScheduledMessage()">Cancel</button>
            </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.data.length" 
        [pageIndex]="0"
        [pageSize]="5"
        [pageSizeOptions]="[5, 10, 50, 100]">
    </mat-paginator>
</div>

MessageListComponent.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatSort, MatPaginator } from '@angular/material';
import { MessageDataTableDataSource } from './message-data-table-datasource';
import { MessageService } from '../message.service';
import { MessageData } from '../../data-model/MessageData';

@Component({
  selector: 'app-message-list',
  templateUrl: './message-list.component.html',
  styleUrls: ['./message-list.component.css']
})
export class MessageListComponent implements OnInit {

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  dataSource: MessageDataTableDataSource;
  displayedColumns = ['id', 'messageText', 'deliveryDate', 'status', 'action'];

  constructor(private messageService: MessageService) { }

  ngOnInit() {
    this.messageService.getMessages().subscribe(
      (messageData: MessageData[]) => {
        this.dataSource = new MessageDataTableDataSource(this.paginator,
           this.sort, messageData);
      },
      (error) => console.log(error)
    );
  }

}

期待友善的建议。 谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用 *ngIf safe navigation operator (?) .

处理此错误

原因: 当您尝试在组件上设置实际值之前尝试访问模板中的数据源时,只会发生控制台错误。发生这种情况是因为数据是异步分配的。

解决方案:

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