首页 > 解决方案 > 在 Angular 9 中更新 CLI 生成的材料表的内容

问题描述

所以我有一个应用程序,用户上传文件,在后端做了一些操作后,我发回了一个 JSON 对象列表。我已经生成了一个材料表来显示内容,现在发生的是我的材料表数据源没有不更新。就像我上传文件并查看数据时一样,它显示了正确的列表,但是当我返回并上传不同的文件并再次查看内容时,表格内容没有得到更新,仍然显示第一个文件(一开始上传的文件)。现在我明白了为什么会出现问题,我没有将数据源订阅到服务器发送的更改,我尝试添加它,但它仍然没有改变。你能帮帮我吗?

test-table-datasource.ts

import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';

// TODO: Replace this with your own data model type
export interface TestTableItem {
  name: string;
  id: number;
}

// TODO: replace this with real data from your application
const EXAMPLE_DATA: TestTableItem[] = [
];

/**
 * Data source for the TestTable view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class TestTableDataSource extends DataSource<TestTableItem> {
  data: TestTableItem[] = EXAMPLE_DATA;
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
    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<TestTableItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

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

  /**
   *  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: TestTableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    if( data.length -  startIndex < this.paginator.pageSize ){
      let diff = this.paginator.pageSize -(data.length - startIndex)
      for(let i=0 ; i<diff;i++){
        data.push(Object.create(null));
      }
    }

    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: TestTableItem[]) {
    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: string | number, b: string | number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

test-table.component.ts

import { AfterViewInit, Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { TestTableDataSource, TestTableItem } from './test-table-datasource';
import { SharedDataService } from '../shared-data.service';

@Component({
  selector: 'app-test-table',
  templateUrl: './test-table.component.html',
  styleUrls: ['./test-table.component.css']
})
export class TestTableComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<TestTableItem>;
  @ViewChild('paginator') pageRef : MatPaginator;
  dataSource: TestTableDataSource;
  pagesize:number;
  viewOpened:boolean=false;
  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name'];

  constructor(private sharedData:SharedDataService){}

  ngOnInit() {
    this.dataSource = new TestTableDataSource();
    this.sharedData.watchServerResponse.subscribe(res =>{
      this.dataSource.data = res;
      if(this.viewOpened === true){
        this.table.dataSource = this.dataSource;
      }
    })
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
    this.viewOpened=true;
  }
}

test-table.component.html

<div class="mat-elevation-z8">
  <table mat-table class="full-width-table" 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?.data.length"
      [pageIndex]="0"
      [pageSize]="2"
      [pageSizeOptions]="[2, 3, 5, 25, 50, 100, 250]">
  </mat-paginator>
</div>

我已经看到了一些相关的答案,但是由于我使用 CLI 生成了表格,所以我的情况有所不同,而且我对 Angular 也很陌生。提前致谢

标签: javascriptangulartypescriptpaginationangular-material

解决方案


有一个名为的参数dataSource,您可以在其中直接指定必须在表中使用的数据源。

<mat-table [dataSource]="dataSource">

因此,不要指定,而是this.table.dataSource尝试将其直接绑定到 dataSource。


推荐阅读