我认为情况是,Firebase在获取列表项之前调用了过滤器,当Firebase获取列表项时,会重新初始化过滤后的数组。你需要这样做:
surveyPatients:any;
getFilteredItems(ev: any) {
let val = ev.target.value;
this.initializeSurveyPatients().subscribe(snap => {
this.surveyPatients = snap;
console.log(this.surveyPatients.length);
if (val && val.trim() != '' ) {
this.surveyPatients = this.surveyPatients.filter((item) => {
return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
console.log(this.surveyPatients.length);
}
});
}
initializeSurveyPatients() {
return this.afoDatabase.list('/SurveyPatients', {
query:{
orderByChild: 'district',
equalTo: 'Nalgonda '
}
});
}
如果你在html输入中使用事件,那么每次用户输入一个经过过滤的字母时,你的firebase方法都可以被调用数次,并多次重新加载你的患者列表。
还有一件事,我自己从来没有使用过AngularFire2,但订阅列表并不意味着你在数据库的那个节点上会有一个可观察的?这很糟糕,因为可以在没有进一步警告的情况下重置对象,这真的很糟糕。
您应该有2个患者变量,一个用于在每次更新时接收数据库结果,另一个用于过滤器:
surveyPatients:any; // to be observed
surveyPatientsFiltered: any; // to be used in filter
ionViewWillLoad(){ // WHEN LOADING OR ENTERING PAGE YOU'LL SUBSCRIBE TO THE EVENT AND SAVE THE RESULTS IN YOUR VAR
this.afoDatabase.list('/SurveyPatients',
{
query:{
orderByChild: 'district',
equalTo: 'Nalgonda '
}
}).subscribe(snap => {
this.surveyPatients = snap;
});
}
getFilteredItems(ev: any) {
this.initializeSurveyPatients();
let val = ev.target.value;
console.log(this.surveyPatients.length);
if (val && val.trim() != '' ) {
this.surveyPatientsFiltered = this.surveyPatientsFiltered.filter((item) => {
return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
console.log(this.surveyPatients.length);
}
}
initializeSurveyPatients(){
this.surveyPatientsFiltered = this.surveyPatients;
}
希望这有帮助。