我在使用 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
使用Observable
s 而不是 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 应用程序的链接,现在它尽可能简约地代表问题。