我使用angular5-data-table
来显示我的参与者。最近,我开始在搜索或过滤表时出现错误。错误是:
TypeError:无法读取null的属性“ toLowerCase”
我不知道为什么有null
。我没有上周遇到任何问题,这很奇怪。
我的搜索或过滤html代码是:
<input type="text" class="form-control input-md" placeholder="Search by first name" #query (keyup)="searchParticipant(query.value)" [(ngModel)]="filter.name">
我的component.ts代码是:
searchParticipant(query: string) {
const filteredParticipants = (query) ?
this.participants.filter(p => p.firstName.toLowerCase().includes(query.toLowerCase())) :
this.participants;
this.initializeTable(filteredParticipants);
}
我能够列出所有参与者,并能够浏览页面和排序。但是,过滤将上述错误抛出。我重构了代码,看了看他们的网站,但到目前为止还没有运气。任何帮助将不胜感激。
编辑:这是完整的component.ts文件。请注意,我在这里使用Participant
而不是Member
。但是我有同样的问题。
export class MembersListComponent implements OnInit {
members: Member[];
totalMembers: any;
items: Member[] = [];
itemCount: number;
filter: any = {};
tableResource: DataTableResource<Member>;
allMembers: Member[];
constructor(private memberService: MemberService, private alertifyService: AlertifyService, private route: ActivatedRoute) { }
ngOnInit() {
this.loadMembers();
}
private initializeTable(members: Member[]) {
this.tableResource = new DataTableResource(members);
this.tableResource.query({ offset: 0 }).then(items => this.items = items);
this.tableResource.count().then(count => this.itemCount = count);
}
reloadItems(params: any) {
if (!this.tableResource) { return; }
this.tableResource.query(params).then(items => this.items = items);
}
loadMembers() {
this.memberService.getAllMembers().subscribe((members: Member[]) => {
this.members = members;
this.initializeTable(members);
}, error => {
this.alertifyService.error(error);
});
}
searchMember(query: string) {
const filteredMembers = (query) ?
this.members.filter(p => p.firstName.toLowerCase().includes(query.toLowerCase())) :
this.members;
this.initializeTable(filteredMembers);
}
}
答案 0 :(得分:0)
我强烈建议您将代码分成小块,这将有助于您正确调试,并且在使用它之前,您应该验证firstName是否存在于当前对象中
searchParticipant(query: string) {
let filteredParticipants = [];
if (query) {
filteredParticipants = this.participants.filter(p => {
if (p.firstName && p.firstName.toLowerCase().includes(query.toLowerCase())) {
return true;
}
return false;
}
this.initializeTable(filteredParticipants);
}