【问题标题】:Angular 5 typeerror:Angular 5 类型错误:
【发布时间】:2018-08-10 00:17:18
【问题描述】:

我在一个项目中使用 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 的类型仍然是字符串,输入也是字符串。 但是,就好像我不能使用字符串方法只是因为打字稿被合并了。

【问题讨论】:

  • 看起来name 未定义。在过滤器回调中设置断点并确保已定义。

标签: angular typescript typeerror undefined-function


【解决方案1】:

您似乎正在尝试对集合 candidates 执行过滤操作,即使它尚未从 API 服务器检索到。通过查看您的 UI,您似乎没有执行任何基于查询字符串的远程过滤。在这种情况下,我建议在开始时检索candidates 集合,然后将input 框禁用/只读。这样可以避免发生意外错误。

HTML

<input #f (input)="filterResults(f.value)" [readonly]="candidates.length"/>

<div *ngIf="filteredCandidates.length">
    <ul class="filtered-candidates-list">
        <li *ngFor="let candidate of filteredCandidates">
            {{ candidate.name }}
        </li>
    </ul>
</div>

组件

private queryString: string;
private candidates: Candidate[] = []
private filteredCandidates: Candidate[] = [];

getResults(){
    this.candidatesService.filterCandidates().subscribe(
       candidates => this.candidates = candidates || []
    );
};

filterResults(queryString) {
    if (!queryString) {
      return;
    }
    else {
      this.candidates.filter(c => { c.name && c.name.indexOf(queryString) >= 0 });
    }
}

【讨论】:

  • 感谢您的建议。数据库似乎有问题,其中一个对象没有名称属性。不过还是谢谢你的建议。
【解决方案2】:

如果在某些情况下没有定义 c.name,您可以像这样进行检查:

  this.candidates.filter(c => { 
      return c.name !== null && c.name.indexOf(queryString) >= 0 
  });

在这里,!== null 将检查 null 和未定义的值。

【讨论】:

  • 谢谢,你说得对。数据库中的对象没有属性名称。
【解决方案3】:

多么愚蠢的错误。我不得不做一些错误处理。在数据库中,其中一个对象没有属性名称(未定义)。所以当循环到达那里时,代码就坏了。我必须更好地处理错误。不过还是谢谢大家的建议。

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    相关资源
    最近更新 更多