简体   繁体   中英

Angular push array items to new array

I have returned data from server like:

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

What I try to do is to push all items from wishes to an array named products but it returns undefined in view.

Code

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>

PS

with console.log(res['wishes']); I can get my wishes part but somehow in my loop code (above) it doesn't work Maybe I placed it wrong

Any idea?

As per your data the product is nested inside wish object so you can access it like this:

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

you can directly use data.wishes in ngFor.

StackBlitz URL

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM