我正在执行一个搜索栏,它过滤了我想要的方式,但是2秒后,它再次显示了整个数组,我真的不明白为什么。
谢谢你的帮助。
这是.ts
getCatalog() {
this.http.get('url', {}, {}).then(data => {
console.log("Data:", JSON.parse(data.data));
this.catalogList = JSON.parse(data.data);
// console.log(data.status);
// console.log(data.data); // data received by server
// console.log(data.headers);
})
.catch(error => {
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
}
getItems(ev: any) {
// Reset items back to all of the items
this.getCatalog();
// set val to the value of the searchbar
let val = ev.target.value;
//console.log("VALUE", ev);
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.catalogList = this.catalogList.filter((item) => {
console.log("ITEM", item)
return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}这就是我拥有*ngFor的地方
<ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
<ion-grid>
<ion-row *ngFor="let item of catalogList">
Other code here发布于 2017-11-22 13:02:08
我认为问题在于,您的HTTP请求在筛选完数组后就会完成,这将使catalogList在过滤之后接收解析的JSON,这就是为什么它会重置。
当ser每次在搜索栏中键入某些内容时,您真的需要从服务器获取目录吗?你的目录有那么动感吗?如果不是,您可以在用户进入页面并创建另一个对象以便在筛选器中使用时,将其保存在catalogList中:
public catalogListFiltered: any[] = []; // CREATE A NEW VARIABLE THAT'LL BE USED ON YOUR NGFOR
ionViewDidEnter() { // or ionViewDidLoad, depends on what lifecycle you need
this.http.get('url', {}, {}).then(data => {
this.catalogList = JSON.parse(data.data);
this.initializeCatalogs();
});
}
// THIS'LL SET YOUR FILTERED ARRAY TO THE FIRST/FULL VERSION OF YOUR CATALOG
initializeCatalogs(){
this.catalogListFiltered = this.catalogList;
}
getItems(ev: any) {
// Reset items back to all of the items
this.initializeCatalogs();
// set val to the value of the searchbar
let val = ev.target.value;
//console.log("VALUE", ev);
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.catalogList = this.catalogList.filter((item) => {
console.log("ITEM", item)
return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}如果你真的需要每次调用你的API来获得你的目录,只需使用承诺。
getCatalog = (): Promise<any> {
return new Promise<any>(resolve => {
this.http.get('url', {}, {}).then(data => {
resolve(JSON.parse(data.data));
});
});
}
// maybe this'll have the same effect as the above, maybe someone can say if that'll work with some changes on your 'getItem' method:
// getCatalog(){ return this.http.get('url', {}, {}); };
getItems(ev: any) {
// Reset items back to all of the items
this.getCatalog().then(res => {
this.catalogList = res;
// set val to the value of the searchbar
let val = ev.target.value;
//console.log("VALUE", ev);
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.catalogList = this.catalogList.filter((item) => {
return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
});
}希望这能有所帮助。
https://stackoverflow.com/questions/47434318
复制相似问题