简体   繁体   English

角度将数组项推送到新数组

[英]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.我试图做的是将所有项目从wishes推送到一个名为products的数组,但它在视图中返回 undefined 。

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']);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:根据您的数据,该product嵌套在wish对象中,因此您可以像这样访问它:

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

you can directly use data.wishes in ngFor.你可以直接在 ngFor 中使用 data.wishes。

StackBlitz URL 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