简体   繁体   English

更新 Angular 中 CLI 生成材料表的内容 9

[英]Updating the contents of a CLI Generated Material Table in Angular 9

So I have an application, the user uploads the file and after doing some operations on the backend I send back a list of JSON Object.And I have generated a material table to show the contents, now what's happening is that my material table dataSource doesn't get updated.所以我有一个应用程序,用户上传文件,在后端做了一些操作后,我发回了 JSON Object 的列表。我已经生成了一个材料表来显示内容,现在发生的是我的材料表数据源没有不更新。 Like when I upload the file and I am viewing the data, it shows the correct lists, however when I go back and upload a different file and view the content again, the table content doesn't get updated and still shows the first file(the file uploaded at the very beginning).就像我上传文件并查看数据时一样,它显示了正确的列表,但是当我 go 返回并上传不同的文件并再次查看内容时,表格内容没有得到更新,仍然显示第一个文件(一开始上传的文件)。 Now I understand why the problem is occurring, I have not subscribed the dataSource to the changes sent by the server and I tried adding that but still it doesn't changes.现在我明白了为什么会出现问题,我没有将数据源订阅到服务器发送的更改,我尝试添加它,但它仍然没有改变。 Can you please help me here?你能帮帮我吗?

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>

I have seen some related answers, but since I have generated the table using CLI, my situation is different, also I am quite new to Angular.我已经看到了一些相关的答案,但是由于我使用 CLI 生成了表格,所以我的情况有所不同,而且我对 Angular 还是很陌生。 Thanks in advance提前致谢

has a parameter called dataSource where you can direcly specify the dataSource that has to be used in the table.有一个名为dataSource的参数,您可以在其中直接指定必须在表中使用的数据源。

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

So, instead of specifiing this.table.dataSource , try binding it directly to dataSource.因此,不要指定this.table.dataSource ,而是尝试将其直接绑定到 dataSource。

Try this, in your test-table-datasource.ts试试这个,在你的test-table-datasource.ts

  // Add these lines
  dataChange = new EventEmitter();
  updateData(data = []) {
    this.data = data.length ? data : this.data;
    this.dataChange.emit();
  }
  // .
  // .
  // Add one observable to the list
    const dataMutations = [
      observableOf(this.data),
      this.dataChange, // <- here!
      this.paginator.page,
      this.sort.sortChange,
    ];

In your test-table.component.ts just update one line在您的test-table.component.ts只需更新一行

  ngOnInit() {
    this.dataSource = new TestTableDataSource();
    this.sharedData.watchServerResponse.subscribe(res =>{
      this.dataSource.updateData(res); // <- this one
      if(this.viewOpened === true){
        this.table.dataSource = this.dataSource;
      }
    })
  }

And of course do the imports, good luck!当然做进口,祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM