簡體   English   中英

從數組中刪除以前的值並用新值更新

[英]Remove previous values from array and update with new ones

在我的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);
        }
      }));
    });
  }

導航欄(下拉).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

我也注意到我正在一個接一個地接收“飲料”,這是控制台的屏幕截圖

因此,取決於“ this.drinks.length”,我得到的是一個數組,其中每張新卡都與舊卡合並,或者它只顯示一張卡(所選成分對其進行了更新)...我可以不了解如何解決此問題... 我只想在每次選擇項目時更新視圖(並清空數組)

看來您正在循環中調用this.onSearch.emit() ,因此每喝一杯它都會被觸發...

最好先使用2個API調用構建數組,然后再調用this.onSearch.emit()來設置您的this.drinks數組: this.drinks = $event

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM