我发现当我尝试调用函数时,必须首先调用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
}
如果函数按顺序调用。我的结果将是
initializeItems()
可变的tempItem将是//完整列表
然后
checkList()
可变tempItems将// //可搜索的下拉列表中的过滤列表
答案 0 :(得分:1)
await
用于诺言。由于initializeItems不返回承诺,所以await实际上并不等待任何东西。您需要修改initializeItems才能返回承诺。我的猜测是,您希望subscribe回调仅被调用一次,然后应会解决promise,因此您需要这样做:
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
});
}
}