角材料表TypeError:无法读取未定义的属性“汽车”

时间:2018-12-25 21:14:16

标签: angular typescript angular-material ngoninit angular-material-table

我在角材料表(Angular Material Table)上遇到问题

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

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

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();
  }
}

cars-table-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);
}

cars.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);
  }

打印出:

enter image description here enter image description here

该页面仍然可以加载所有内容,但是我无法通过该方法添加汽车,因为它们确实已添加到数据库中,但是尽管调用了文档中提到的this.table.renderRows()也没有在视图中更新:

  

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

我尝试使ngOnInit使用Observable而不是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);
}

错误顺序更改为:

enter image description here enter image description here

这意味着错误发生在

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

我已经用.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);
  }

现在它可以工作了,但这有点hack。我不知道为什么,但是只要Angular的生命周期钩子中的asyc代码在哪里,钩子就会在异步代码完成之前完成。我不知道为什么 看到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应用程序的链接,现在它尽可能简化以表示问题。

2 个答案:

答案 0 :(得分:3)

cars之前创建constructor对象。 Angular在运行应用程序时不知道该属性。

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

constructor () { }

这只是为了告诉angular,模板将包含一系列car类型。 (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:这只是为了快速修复,我将尝试找出一种更优雅的方法,因为以前我已经处理过此类问题,补丁程序可以运行,但是看不到OOP。

答案 1 :(得分:1)

connect()方法返回一个Observable<CarsTableItem[]>。并且由于getPagedDatagetSortedData均未返回Observable,因此初始化CarsTableDataSource和材料表时会发生由于延迟而导致的未定义。

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

最佳做法是,您应在CarsService的实现中注入CarsTableDataSource,并使其处理数据加载和分页内容。