1

我在使用 Angular 材料表(Angular 材料表)时遇到问题

我跑来ng generate @angular/material:material-table --name=car-table生成默认的角度表,它工作正常。但是,如果我尝试将数据(汽车)注入它,CarsTableDataSource它就会停止工作。它必须与异步函数和ngOnInit生命周期挂钩相关。

您可以在StackBlitz中查看代码。关键部分在src/app/cars/文件夹中。

汽车.component.ts

import {Component, OnInit, ViewChild} from '@angular/core';
import {Car} from '../car';
import {CarService} from '../car.service';
import {MatPaginator, MatSort, MatTable} from '@angular/material';
import {CarsTableDataSource} from './cars-table-datasource';

@Component({
  selector: 'app-cars',
  templateUrl: './cars.component.html',
  styleUrls: ['./cars.component.css']
})
export class CarsComponent implements OnInit {
  cars: Car[];

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<Car>;
  dataSource: CarsTableDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name', 'img_url'];

  constructor(private carService: CarService) {
  }

  async ngOnInit() {
    console.log('before getting cars: ');
    console.log(this.cars);
    this.cars = await this.carService.getCars().toPromise();
    console.log('got cars:');
    console.log(this.cars);
    this.dataSource = new CarsTableDataSource(this.paginator, this.sort, this.cars);
  }

  add(name: string) {
    name = name.trim();
    if (!name) {
      return;
    }
    this.carService.addCar({name} as Car)
      .subscribe(car => {
        this.cars = [...this.cars, car];
        console.log(this.cars);
        console.log('rendering rows');
        this.table.renderRows();
      });
  }

  delete(car: Car) {
    this.cars = this.cars.filter(c => c !== car);
    this.carService.deleteCar(car).subscribe();
    this.table.renderRows();
  }
}

汽车表datasource.ts

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

/**
 * Data source for the CarsTable view. This class should
 * encapsulate all logic for fetching and manipulating the displayed cars
 * (including sorting, pagination, and filtering).
 */
export class CarsTableDataSource extends DataSource<CarsTableItem> {
  // cars: CarsTableItem[];

  constructor(private paginator: MatPaginator, private sort: MatSort, public cars: Car[]) {
    super();
  }

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

    // Set the paginator's length
    this.paginator.length = this.cars.length;

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

  /**
   *  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 cars (client-side). If you're using server-side pagination,
   * this would be replaced by requesting the appropriate cars from the server.
   */
  private getPagedData(data: CarsTableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  /**
   * Sort the cars (client-side). If you're using server-side sorting,
   * this would be replaced by requesting the appropriate cars from the server.
   */
  private getSortedData(data: CarsTableItem[]) {
    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.html

<div>
  <label>Car name:
    <input #carName />
  </label>
  <!-- (click) passes input value to add() and then clears the input -->
  <button (click)="add(carName.value); carName.value=''">
    add
  </button>
</div>

<h2>My Cars</h2>
<div class="mat-elevation-z8 centered-table-div">
  <table mat-table class="full-width-table" [dataSource]="dataSource" matSort aria-label="Elements">

    <!-- Image Column -->
    <ng-container matColumnDef="img_url">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Image</th>
      <td mat-cell *matCellDef="let row">
        <img [src]="row.img_url" alt="car image" class="car-image"/>
      </td>
    </ng-container>

    <!-- 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.cars.length"
                 [pageIndex]="0"
                 [pageSize]="5"
                 [pageSizeOptions]="[3, 5, 25, 50]">
  </mat-paginator>
</div>

问题在于ngOnInit

  <mat-paginator #paginator
                 [length]="dataSource.cars.length"
                 [pageIndex]="0"
                 [pageSize]="5"
                 [pageSizeOptions]="[3, 5, 25, 50]">
  </mat-paginator>

作为我得到的错误ERROR TypeError: Cannot read property 'cars' of undefined,这意味着dataSource在解析模板时未定义,但函数ngOnInit

  async ngOnInit() {
    console.log('before getting cars: ');
    console.log(this.cars);
    this.cars = await this.carService.getCars().toPromise();
    console.log('got cars:');
    console.log(this.cars);
    this.dataSource = new CarsTableDataSource(this.paginator, this.sort, this.cars);
  }

打印出来:

在此处输入图像描述 在此处输入图像描述

该页面仍会加载所有内容,但我不能例如通过该方法添加汽车,因为它们确实会添加到数据库中,但不会在视图中更新,尽管this.table.renderRows()如文档中所述调用:

由于该表针对性能进行了优化,因此它不会自动检查数据数组的更改。相反,当在数据数组上添加、删除或移动对象时,您可以通过调用其renderRows()方法来触发对表的呈现行的更新。

我尝试ngOnInit使用Observables 而不是 s async/await,但它也不起作用:

  ngOnInit() {
    console.log('before getting cars: ');
    console.log(this.cars);
    this.carService.getCars().subscribe(cars => {
      this.cars = cars;
      console.log('got cars:');
      console.log(this.cars);
      this.dataSource = new CarsTableDataSource(this.paginator, this.sort, this.cars);
    });
  }

如果我不做任何数据库获取 中的东西ngOnInit,那么就没有任何错误。

add()如前所述,我现在也无法添加任何汽车。

如果您需要任何其他信息 - 请随时问我,我会尽快回复。

编辑

如果我将代码编辑为如下所示:

async ngOnInit() {
  console.log('before getting cars: ');
  console.log(this.cars);
  console.log('got cars:');
  this.cars = await this.carService.getCars().toPromise();
  console.log(this.cars);
  this.dataSource = new CarsTableDataSource(this.paginator, this.sort, this.cars);
}

错误的顺序更改为:

在此处输入图像描述 在此处输入图像描述

这意味着错误发生在

this.cars = await this.carService.getCars().toPromise();

我已经尝试过使用 a.subscribe()并在该块中执行所有操作,但那里没有运气。

编辑 2

here(stackoverflow)所述,您必须dataSource使用空白对象初始化,因为在所有微任务完成之前解析视图ngOnInit。在视图初始化之后初始化分页器。

  async ngOnInit() {
    this.dataSource = new CarsTableDataSource(this.paginator, this.sort, []);
    console.log('before getting cars: ');
    console.log(this.cars);
    this.cars = await this.carService.getCars().toPromise();
    console.log('got cars:');
    console.log(this.cars);
    this.dataSource = new CarsTableDataSource(this.paginator, this.sort, this.cars);
  }

现在它可以工作了,但这有点像黑客。我不知道为什么,但是每当 Angular 的生命周期钩子中的异步代码在哪里时,钩子都会在异步代码完成之前完成。我不知道为什么。在它看到await它之后立即退出该函数,并且只有在那之后才被dataSource初始化。我真的很感激解释。

编辑 3

另一种解决方法是在视图中添加空条件运算符,如下所示:

  <mat-paginator #paginator
                 [length]="dataSource?.cars.length"
                 [pageIndex]="0"
                 [pageSize]="5"
                 [pageSizeOptions]="[3, 5, 25, 50]">
  </mat-paginator>

有了这条线:

[length]="dataSource?.cars.length"

由于视图是在 ngOnInit 完成一半时执行的,因此您必须在使用该属性的任何地方添加它,以便在解析视图时它不会进入最终的 html。

编辑 4

我更新了 Stackblitz 应用程序的链接,现在它尽可能简约地代表问题。

4

2 回答 2

3

在. cars_ constructorAngular 在运行应用程序时不知道该属性。

cars: Car[] = [new Car()]

constructor () { }

这只是告诉 Angular 模板将包含一系列汽车类型。(1)

已编辑

CarsTableDataSource做与上面相同的事情。

汽车:汽车[] = [新车()]

并将它们从构造函数中删除。(1)

另一个解决方案是,制作CarsTableDataSource一个 @Injectable 以便将 DI 委托给 Angular。

...
@Injectable({providedIn: 'root'})
export class CarsTableDataSource extends DataSource<CarsTableItem> {

constructor ( private paginator: MatPaginator, private sort: MatSort, public cars: Car[] )

...

}

(1) PD:这只是为了快速修复,我会尝试找到一种更优雅的方法,因为我以前处理过此类问题,并且该补丁有效,但没有看到后续哎呀。

于 2018-12-25T21:19:28.293 回答
1

connect() 方法返回一个Observable<CarsTableItem[]>. 并且由于getPagedData并没有返回 Observable,因此在初始化和 Material TablegetSortedData时会发生由于延迟而导致的未定义。CarsTableDataSource

尝试在.asObservable()这些方法中添加或其他内容。

作为最佳实践,您应该注入CarsService实现CarsTableDataSource并让它处理数据加载和分页的东西。

于 2018-12-25T21:54:01.440 回答