簡體   English   中英

角度將數組項推送到新數組

[英]Angular push array items to new array

我已經從服務器返回數據,如:

{
  user:{id: 1, ......},
  wishes:[
    {id: 3, ......},
    {id: 4, ......}
  ]
}

我試圖做的是將所有項目從wishes推送到一個名為products的數組,但它在視圖中返回 undefined 。

代碼

controller

products: any[] = [];
limit = 10;
loading: any;

async getProducts() {
    this.loading = await this.loadingController.create({
      message: 'Please wait...',
      spinner: 'crescent',
      duration: 2000
    });

    await this.loading.present();

    this.wishlistService.getProducts().subscribe((res) => {
      for (let product of res['wishes']) {
        this.products.push(product);
      }
      this.hideLoading();
    });
  }

  private hideLoading() {
    this.loading.dismiss();
  }

HTML

<ion-row padding *ngIf="products.length>0 else noItem">
  <ion-col size="6" class="prodCard" size-sm *ngFor="let product of products | slice:0:limit">
  //rest of html part
  </ion-col>
</-ion-row>

聚苯乙烯

console.log(res['wishes']); 我可以得到我的願望部分但不知何故在我的循環代碼(上圖)中它不起作用也許我放錯了

任何的想法?

根據您的數據,該product嵌套在wish對象中,因此您可以像這樣訪問它:

for (let wish of res['wishes']) {
    this.products.push(wish.product);
}

你可以直接在 ngFor 中使用 data.wishes。

StackBlitz 網址

 data = {"user":{"id":1,"name":"user name"},"wishes":[{"id":11,"name":"some wish"},{"id":52,"name":"wish item"}]};

 <li *ngFor="let product of data.wishes">{{product.name}}</li>

暫無
暫無

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

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