我在一个项目中使用 Angular 5,我得到一个打字稿错误:
ERROR TypeError: Cannot read property 'indexOf' of undefined
我的代码应该做的是在输入更改时更新模板,如下所示:
模板:
<input #f (input)="filterResults(f.value)"/>
<div *ngIf="filteredCandidates.length">
<ul class="filtered-candidates-list">
<li *ngFor="let candidate of filteredCandidates">
{{ candidate.name }}
</li>
</ul>
</div>
和component.ts:
private queryString: string;
private candidates: Candidate[] = []
private filteredCandidates: Candidate[] = [];
filterResults(queryString) {
this.candidatesService.filterCandidates().subscribe(candidates => this.candidates = candidates);
if (!queryString) {
return;
}
else {
this.candidates.filter(c => { c.name.indexOf(queryString) >= 0 });
}
}
我尝试在 c.name 上使用 .contains() 方法,得到了相同的结果。正如预期的那样,candidate.name 的类型仍然是字符串,输入也是字符串。但是,就像我不能使用字符串方法只是因为打字稿被合并了。