I’ve a virtual scroll list with a search bar using Ionic 2.0.1.
HTML code:
<ion-searchbar (ionInput)=“getItems($event)”>
TS code
getItems(ev: any) {
// Reset items back to all of the items
console.log(“reinitialize”);
this.initializeItems();
// set val to the value of the searchbar
let val = ev.target.value;
console.log("search for: " + val);
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
console.log("filtering");
this.items = this.items.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}
When a try to enter a search text I can see the list getting filtered for a split second and then it goes back to the original state to show all the items again.
UPDATE - with some more debugging I can see that the filter is taking effect in the code but not updating in the list!
UPDATE2 - it all works when items is a fixed array. But when I read items from storage it doesn’t work!
What am I doing wrong?
You are acting as though initializeItems behaves synchronously. You cannot rely on this.items being set to anything until the underlying promise resolves. Return it from initializeItems and chain off that.
initializeItems(): Promise<Item[]> {
// the data service should be responsible for dealing with JSON and getting data into the proper format.
// that should not be client code responsibility
return this.dataService.getItems();
}
this.initializeItems().then((items) => {
this.items = items;
let val = ev.target.value;
if (val && val.trim() != '') {
// do filtering
}
// only in here can you rely on this.items having been received
});
// outside here you cannot rely on this.items not being stale
Thanks @zoinky and @rapropos for helping. I took a hint from @rapropos and was able to resolve the situation like this.
getItems(ev: any) {
// Reset items back to all of the items
console.log("reinitialize");
this.dataService.getItems().then((cItems) => {
if (cItems) {
this.items = JSON.parse(cItems);
// set val to the value of the searchbar
let val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.items = this.items.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}
});
}