首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法读取Angular中未定义数组的属性'filter‘

无法读取Angular中未定义数组的属性'filter‘
EN

Stack Overflow用户
提问于 2018-08-05 02:09:41
回答 2查看 1.6K关注 0票数 2

我有一个数组customerList: Array<String> = [];和一个将值从服务器推送到这个数组的函数。它工作得很好,除了当我在这个数组上使用.filter()时,它给了我未定义的错误。此代码为:

代码语言:javascript
复制
customerList: Array<String> = [];

ngOnInit() {
this.customerService.getCustomers().subscribe(res => {
    this.customers = res;
    for (const cust of res) {
      this.customerList.push(cust.first_name);
    }
  }
);
}

findChoices(searchText: string) {
return this.customerList.filter(item =>
  item.toLowerCase().includes(searchText.toLowerCase())
  ); 
 );
}

HTML代码:

代码语言:javascript
复制
<mwl-text-input-autocomplete-container>
  <input type="text" class="form-control" id="customer_name" name="customer_name" aria-describedby="emailHelp"
                 placeholder="Customer name" formControlName="customer_name" mwlTextInputAutocomplete
                 [findChoices]="findChoices"
                 [getChoiceLabel]="getChoiceLabel" autofocus>
</mwl-text-input-autocomplete-container>

findChoices()中的customerList.filter()出现错误。

附注:我使用的是this package

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-05 02:52:53

由于您将函数对象findChoices作为值传递给[findChoices],因此this的值不会绑定到您的组件,因此this.customerList将是未定义的。

您可以使用闭包来确保[findChoices]customerList可见,具体步骤如下:

  1. 更改findChoices实现以返回可用作[findChoices]的值的函数-即接受字符串参数的函数。

findChoicesIn( item.toLowerCase().includes(searchText.toLowerCase()));){findChoicesIn (searchText) => list.filter(item => list};

  • 使用这样生成的函数作为[findChoices]的值

findChoices="findChoicesIn(customerList)"

票数 4
EN

Stack Overflow用户

发布于 2018-08-05 02:11:46

确保您的customerList为空或null,只需添加检查

代码语言:javascript
复制
if(this.customerList && this.customerList.length > 0){
  return this.customerList.filter(item =>
  item.toLowerCase().includes(searchText.toLowerCase())
  ); 
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51688345

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档