【问题标题】:ERROR TypeError: Cannot read property 'toLocaleLowerCase' of undefined core.js:5967错误类型错误:无法读取未定义 core.js:5967 的属性“toLocaleLowerCase”
【发布时间】:2021-04-05 22:10:54
【问题描述】:

Component.ts

branches: any = [];
branchName: string; // any
ngOnInit(): void {
    // this.refreshBranchList();
    this.service.getBranchList().subscribe((response: any) => {
      this.branches = response;
});
}
Search() {
if (this.branchName !== "") {
  this.branches = this.branches.filter((res: { branchName: string; }) => {
    return res.branchName.toLocaleLowerCase().match(this.branchName.toLocaleLowerCase());
  })
} else if (this.branchName == "") {
  this.ngOnInit();
}

}

Component.html

<div class="d-flex float-right">
  <input type="text" class="form-control" placeholder="Search here" [(ngModel)]="branchName" (ngModelChange)="Search()">
</div>

它正在按预期搜索值。但是控制台中有一个我不熟悉的错误。有什么我想念的请告诉我。

【问题讨论】:

  • 错误是自己说的。 res.branchNamethis.branchName 未定义,并且无法在其中找到函数 .toLocaleLowerCase()。尝试在调用.toLocaleLowerCase()之前添加检查值是否存在。

标签: angular typescript django-rest-framework


【解决方案1】:

尝试改变这一点

return res.branchName.toLocaleLowerCase().match(this.branchName.toLocaleLowerCase());

到这里

return res.branchName?.toLocaleLowerCase().match(this.branchName?.toLocaleLowerCase());

【讨论】:

  • 代码不适用于这些?。我不知道为什么,但谢谢你的帮助
  • this.branchName?.toLowerCase() => ?这意味着如果有分支名称,则调用 toLowerCase()。您收到错误,因为当您尝试到达分支名称时,分支名称未定义。重新考虑您的逻辑,即尝试在不初始化分支名称的情况下访问它。
【解决方案2】:

你必须验证this.branchName的值

试试这个方法:

branches: any = [];
    branchName: string; // any
    ngOnInit(): void {
        // this.refreshBranchList();
        this.service.getBranchList().subscribe((response: any) => {
          this.branches = response;
    });
    }

    Search() {
      if (this.branchName && this.branchName !== "") {
        this.branches = this.branches.filter((res: { branchName: string; }) => {
        res.branchName? return res.branchName.toLocaleLowerCase().match(this.branchName.toLocaleLowerCase()): return [];
      })
    } else if (this.branchName == "") {
      this.ngOnInit();
    }
  }

【讨论】:

  • 实际上这些(?)不起作用,所以我尝试了 if else 为这样的分支名称: if (res.branchName == "") { return res.branchName.toLocaleLowerCase().match(this .branchName.toLocaleLowerCase()); } 其他 { 返回 []; }
【解决方案3】:

就像 Nik 在他的评论中所说, res.branchName 或 this.branchName 是未定义的。

所以要么定义你的对象,如果它们是未定义的,或者使用 ?-operator for res?.branchName?.toLocaleLowerCase() 和 this.branchName?.toLocaleLowerCase(),如果视图是在你的属性被分配之前渲染的价值。

【讨论】:

    猜你喜欢
    • 2020-03-02
    • 2020-07-22
    • 2021-03-12
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多