我发现当我尝试调用函数时,需要首先调用 initializeItems(( 但是 checkList(( 在 initializeItems(( 之前被调用
initializeItems() {
this.dataService.readLocalData().subscribe( data => {
console.log('Local Data');
this.items = data;
// console.log(this.items);
this.tempItems = [];
for (const i of this.items.material ){
console.log(i['material-name']);
this.tempItems.push( i['material-name'] );
}
console.log('***********************************************');
console.log(this.tempItems);
});
}
checkList(ev: any){
// set val to the value of the searchbar
const val = ev.target.value;
console.log(val);
console.log(this.tempItems);
// if the value is an empty string don't filter the items
if (val && val.trim() !== '') {
this.tempItems = this.tempItems.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
});
}
}
async getItems(ev: any) {
// Reset items back to all of the items
await this.initializeItems(); //This need to execute first
await this.checkList(ev); //But this getting executed
}
如果函数按顺序调用。我的结果将是
初始化项((
可变临时项将是//完整列表
然后
清单((
变量 tempItems 将是//从可搜索的下拉列表中过滤列表
await
用于承诺。由于 initializeItems 不返回承诺,因此 await 实际上不会等待任何东西。您需要修改初始化项以返回承诺。我的猜测是,您希望订阅回调只调用一次,此时承诺应该解析,因此您需要这样做:
initializeItems() {
return new Promise((resolve) => { // <---- creating a promise
this.dataService.readLocalData().subscribe( data => {
console.log('Local Data');
this.items = data;
// console.log(this.items);
this.tempItems = [];
for (const i of this.items.material ){
console.log(i['material-name']);
this.tempItems.push( i['material-name'] );
}
console.log('***********************************************');
console.log(this.tempItems);
resolve(); // <-- resolving the promise
});
}
}