我有一个数组customerList: Array<String> = [];
和一个将值从服务器推送到这个数组的函数。它工作得很好,除了当我在这个数组上使用.filter()
时,它给了我未定义的错误。此代码为:
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代码:
<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
发布于 2018-08-05 02:52:53
由于您将函数对象findChoices
作为值传递给[findChoices]
,因此this
的值不会绑定到您的组件,因此this.customerList
将是未定义的。
您可以使用闭包来确保[findChoices]
对customerList
可见,具体步骤如下:
findChoices
实现以返回可用作[findChoices]
的值的函数-即接受字符串参数的函数。findChoicesIn( item.toLowerCase().includes(searchText.toLowerCase()));){findChoicesIn (searchText) => list.filter(item => list};
[findChoices]
的值findChoices="findChoicesIn(customerList)"
发布于 2018-08-05 02:11:46
确保您的customerList
为空或null,只需添加检查
if(this.customerList && this.customerList.length > 0){
return this.customerList.filter(item =>
item.toLowerCase().includes(searchText.toLowerCase())
);
}
https://stackoverflow.com/questions/51688345
复制相似问题