我已经创建了在我的项目中创建搜索功能的在线购物应用程序。我列出了客户向特定商店下达的所有订单。现在我想在订单详细信息上向店主提供搜索功能。但我有问题说
“TypeError:无法读取未定义的属性'过滤器'
以下是我的代码: html的:
<ion-searchbar [(ngModel)]="terms" (ionInput)="getItems($event)"></ion-searchbar>
.TS:
loadedCountryList: Array<any>;
countryList: Array<any>;
countryRef: firebase.database.Reference;
ionViewDidLoad() {
this.countryRef = firebase.database().ref('/order_details');
this.countryRef.on('value', countryList => {
let countries = [];
countryList.forEach( country => {
countries.push(country.val());
return false;
});
this.countryList = countries;
this.loadedCountryList = countries;
});
}
initializeItems(): void {
this.countryList = this.loadedCountryList;
}
getItems(searchbar) {
// Reset items back to all of the items
this.initializeItems();
// set q to the value of the searchbar
var q = searchbar.srcElement.value;
console.log('q =' + q);
// if the value is an empty string don't filter the items
if (!q) {
return;
}
this.countryList = this.countryList.filter((v) => {
if (v.name && q) {
if (v.name.toLowerCase().indexOf(q.toLowerCase()) > -1) {
return true;
}
return false;
}
});
console.log(q, this.countryList.length);
}
答案 0 :(得分:2)
好的,所以你在页面加载后检索所有项目。这可能有效,但随后可能会发生错误,当您键入时,数据尚未完成加载。现在你说这不是问题,但它可能会在以后成为一个问题,所以我们也要解决它。
所以让我们重写一下你的代码吧。
<ion-searchbar *ngIf="allCountries" [(ngModel)]="terms" (ionInput)="getItems()"></ion-searchbar>
<!-- show a loading paragraph when countries are being fetched -->
<p *ngIf="!allCountries">Loading....</p>
你的ts :(将loadedCountryList
重命名为allCountries
因为我更喜欢它了
allCountries: Array<any>;
countryList: Array<any>;
countryRef: firebase.database.Reference;
ionViewDidLoad() {
this.countryRef = firebase.database().ref('/order_details');
this.countryRef.on('value', countryList => {
let countries = [];
countryList.forEach( country => {
countries.push(country.val());
return false;
});
this.countryList = countries;
this.allCountries = countries;
});
}
getItems() {
// also check for no input
if (!this.terms || this.terms == '') {
// if no term is entered you might want to reset the search
this.countryList = this.allCountries;
return;
}
// allCountries isn't edited by the filter function so you can use that one
this.countryList = this.allCountries.filter((v) => {
if (v.name) {
if (v.name.toLowerCase().indexOf(this.terms.toLowerCase()) > -1) {
return true;
}
return false;
}
});
}
然后在某处显示您的countryList
: