当我在mat-cards
中显示数据时,代码工作正常,这意味着我正确地获取数据。但是,当我试图在mat-tables
中显示它时,我会收到索引错误。我也导入了matTableDataSource
,DataSource
,CdkTableModule
和MatTableModule
。
Component.ts
export class DriversComponent {
constructor(private webService : WebService, private route: ActivatedRoute, private auth: AuthService) {}
ngOnInit(){
var name = this.route.snapshot.params['name'];
this.webService.getDrivers(name);
this.webService.getUser().subscribe();
let dataSource = this.webService.getDrivers(name);
let displayedColumns = ['id','name','lastname'];
}
Component.html
<div *ngFor="let driver of webService.drivers | async">
<mat-table #table [dataSource]="dataSource" [@movePanel]='state'>
<ng-container matColumnDef="id">
<mat-header-cell *matHeaderCellDef>ID</mat-header-cell>
<mat-cell *matCellDef="let lesson">{{driver.employeeId}}</mat-cell>
</ng-container>
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef>First Name</mat-header-cell>
<mat-cell *matCellDef="let lesson">{{driver.firstName}}</mat-cell>
</ng-container>
<ng-container matColumnDef="lastname">
<mat-header-cell *matHeaderCellDef>Last Name</mat-header-cell>
<mat-cell *matCellDef="let lesson">{{driver.lastName}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
</div>
webservice.ts
private driverStore = [];
private driverSubjet = new Subject();
drivers = this.driverSubjet.asObservable();
constructor(private http: Http, private sb: MatSnackBar, private auth: AuthService) {
this.getDrivers('');
}
getDrivers(user) {
user = (user) ? '/history/' + user : '';
this.http.get(this.BASE_URL + '/employee' + user).subscribe(response => {
this.driverStore = response.json();
this.driverSubjet.next(this.driverStore);
}, error => {
this.handleError("Unable to get drivers");
});
}
答案 0 :(得分:0)
不使用driver
指令中的*ngFor
变量,而是使用lesson
*matCellDef
变量
<mat-table #table [dataSource]="dataSource" [@movePanel]='state'>
<ng-container matColumnDef="id">
<mat-header-cell *matHeaderCellDef>ID</mat-header-cell>
<mat-cell *matCellDef="let lesson">{{lesson.employeeId}}</mat-cell>
</ng-container>
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef>First Name</mat-header-cell>
<mat-cell *matCellDef="let lesson">{{lesson.firstName}}</mat-cell>
</ng-container>
<ng-container matColumnDef="lastname">
<mat-header-cell *matHeaderCellDef>Last Name</mat-header-cell>
<mat-cell *matCellDef="let lesson">{{lesson.lastName}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
您可能根本不需要*ngFor
,因为mat-table
会为您显示数据,您只需要提供数据源。
请注意,您可能需要更改实施getDrivers
功能的方式,因为您没有返回任何内容!