在我的PWA中,我正在发出http请求,并用响应填充翻转卡。 请求取决于所选的值。
问题是:当我从下拉菜单中选择一个项目时,它发出请求并显示由该响应填充的翻页卡。但是,当我选择另一个项目时,它会发出请求并添加新的卡片,而不会清除先前卡片的视图(数组)。
searchByIngredient.component.ts
search() {
this.drinksapi.get(this.selectedIngredient.name).subscribe(data => {
const a = data[`drinks`];
a.map((y: { idDrink: any; }) => this.drinksapi.detailsCocktails(y.idDrink).subscribe(res => {
const b = res[`drinks`];
for (y of b) {
const obj = Object.assign({}, y);
this.onSearch.emit(obj);
}
}));
});
}
Navbar(dropdown).component.html
<ng-select [items]="ingredients"
bindLabel="name"
placeholder="Search By Ingredient"
[(ngModel)]="selectedIngredient"
(ngModelChange)="search()">
</ng-select>
App.Component.ts(可能是此代码中的问题)
export class AppComponent {
title = 'CocktailDB';
drinks: Array<any> = [];
onSearch($event: any) {
// this.drinks.length = 0;
if (this.drinks !== []) {
this.drinks.push($event);
}
console.log('drinks', this.drinks);
} // end onSearch
I've noticed also that I'm recieving "Drinks" one by one, here's a screenshot of the console
因此取决于“ this.drinks.length”,我得到的是一个数组,其中每张新卡都与旧卡合并,或者它仅显示一张卡(所选成分对其进行了更新)...我不明白如何解决此问题... 我只想在每次选择项目时更新视图(并清空数组)
答案 0 :(得分:0)
似乎您正在循环中调用this.onSearch.emit()
,因此每喝一杯酒都会触发该事件……
最好先使用2个API调用构建数组,然后再调用this.onSearch.emit()
来设置this.drinks
数组:this.drinks = $event