【发布时间】:2019-05-18 10:31:02
【问题描述】:
使用排序标题实现 AngularMaterial 表我在控制台中收到此错误:
错误类型错误:无法设置未定义的属性“排序” 在
终端中的这个错误:
错误 TS2740:“MatTableDataSource”类型缺少“Employee[]”类型的以下属性:length、pop、push、concat 等 24 个。
错误 TS2322:类型 'MatSort' 不可分配给类型 '(compareFn?: (a: Employee, b: Employee) => number) => Employee[]'。
类型“MatSort”不匹配签名“(compareFn?: (a: Employee, b: Employee) => number): Employee[]”。
我无法从我这里得到它想要的东西。我将不胜感激任何提示!
我使用了 AngularMaterial 文档中的代码,但数据接口除外。这可能是一个问题吗?
员工列表组件
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatSort, MatTableDataSource } from '@angular/material';
import { AngularFirestore } from '@angular/fire/firestore';
import { EmployeeService } from '../shared/employee.service';
import { Employee } from '../shared/employee';
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.scss']
})
export class EmployeeListComponent implements OnInit {
displayedColumns: string[] = ['fullname', 'position', 'mobile'];
dataSource;
@ViewChild(MatSort) sort: MatSort;
constructor(private service: EmployeeService) { }
ngOnInit() {
this.service.getEmployees().subscribe(employees => {
this.dataSource = new MatTableDataSource(employees);
console.log(this.dataSource);
});
this.dataSource.sort = this.sort;
}
}
员工列表 HTML
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
<!-- Position Column -->
<ng-container matColumnDef="fullname">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Full Name </th>
<td mat-cell *matCellDef="let element"> {{element.fullname}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Position </th>
<td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="mobile">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Mobile </th>
<td mat-cell *matCellDef="let element"> {{element.mobile}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
员工服务
getEmployees() {
return this.firestore.collection<Employee>('employees')
.snapshotChanges()
.pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data } as Employee;
})
)
);
}
员工类
export class Employee {
id: string;
fullname: string;
empCode: string;
position: string;
mobile: string;
}
【问题讨论】:
-
您可以尝试设置排序操作的超时时间,直到获取数据为止,方法是在 console.log之后的 ngOnInit 内添加
setTimeout(() => this.dataSource.sort= this.sort);> 线。 -
setTimeout()工作了吗? -
@Karthik_Siddh 我已经用 ngAfterViewInit 解决了这个问题,并将一些代码移到了订阅部分。解决了错误问题的方法对我很有用,但由于某些原因我的排序仍然不起作用。也许你知道为什么?我将不胜感激任何提示
标签: angular angular-material frontend angular-material-7