我有一个带有客户端筛选的Angular Material Table,在其中我从服务中检索数据。当我的过滤器可以正确处理硬编码数据时,我收到一条错误消息:自从切换到服务中检索数据以来,无法将属性'filterPredicate'设置为undefined。数据可以正确显示在我的表格中,但无法过滤。
export class MessageTableComponent implements OnInit {
datasource: any;
}
ngOnInit() {
this.messageService.getMessageTableData().subscribe(
response => {
this.dataSource = new MatTableDataSource(response);
console.log(response);
}
);
this.RequestIdFilter.valueChanges.subscribe((RequestIdFilterValue) => {
this.filteredValues['RequestID'] = RequestIdFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
});
this.RequestStatusFilter.valueChanges.subscribe((RequestStatusFilterValue) => {
this.filteredValues['RequestStatus'] = RequestStatusFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
});
this.RequestorNameFilter.valueChanges.subscribe((RequestorNameFilterValue) => {
this.filteredValues['RequestorName'] = RequestorNameFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
});
this.ApproverNameFilter.valueChanges.subscribe((ApproverNameFilterValue) => {
this.filteredValues['ApproverName'] = ApproverNameFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
});
this.SubjectFilter.valueChanges.subscribe((SubjectFilterValue) => {
this.filteredValues['Subject'] = SubjectFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
});
this.MessageStatusFilter.valueChanges.subscribe((MessageStatusFilterValue) => {
this.filteredValues['MessageStatus'] = MessageStatusFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
});
this.SubmissionFromDateFilter.valueChanges.subscribe((SubmissionFromDateFilterValue) => {
this.filteredValues['SubmissionFromDate'] = SubmissionFromDateFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
});
this.SubmissionToDateFilter.valueChanges.subscribe((SubmissionToDateFilterValue) => {
this.filteredValues['SubmissionToDate'] = SubmissionToDateFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
});
this.dataSource.filterPredicate = this.customFilterPredicate();
this.dataSource.sort = this.sort;
}
customFilterPredicate() {
.....
}
错误显然在倒数第二行。 messageService是我用来检索数据的服务,其余代码用于在任何列的值更改时随时过滤数据。在此之下,我有customFilterPredicate函数,它为每列定义过滤器。
我不明白这是什么问题。我已经在ngOnInit中定义了dataSource,那么为什么会出现错误以及如何解决呢?
答案 0 :(得分:2)
当此行“ this.dataSource.filterPredicate = this.customFilterPredicate();”未返回来自您服务的调用。被执行...
我们知道异步调用会花费一些时间(与获取硬编码数据相比)...
this.dataSource.filterPredicate = this.customFilterPredicate();
this.dataSource.sort = this.sort;
尝试将这两行(上方)放在服务调用的finally块中,我也包括一个error块,您应该始终必须处理任何错误...
this.messageService.getMessageTableData().subscribe(
response => {
this.dataSource = new MatTableDataSource(response);
console.log(response);
}
,errorResponse => { console.log(errorResponse); }
,()=> {
this.dataSource.filterPredicate = this.customFilterPredicate();
this.dataSource.sort = this.sort;
}
);