gpt4 book ai didi

javascript - Angular 将数组项推送到新数组

转载 作者:行者123 更新时间:2023-11-30 19:18:15 24 4
gpt4 key购买 nike

我从服务器返回的数据如下:

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

我尝试做的是将所有项目从 wishes 推送到名为 products 的数组,但它在 View 中返回未定义。

代码

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);
}

关于javascript - Angular 将数组项推送到新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57765321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com