Вытолкнуть ArrayItem из другого массива в Angular

Im in a situation where I need to push an array item from another array.

export class Products {
    ProductCat: string;
    Products: number;
    Sold: number;
}

export class ProdCats {
    Id: number;
    Category: string;
}

prodCats = ProdCats[];
products Products[];

//I get all the product categories here
this.prodCats = await this.service.getProdCats().toPromise();

now I want to fill my "products" array like this:
for (let i = 0; i < this.prodCats.length; i++) {
  var item = {
    "ProductCat": this.prodCats[i].Category,
    "Products": 0, //want to add default value 0 later on I will update these
    "Sold": 0 //want to add default value 0 later on I will update these
  };
  this.products.push(item);
}

I dont know whether this approach is efficient way, but it fails for me with the error:

core.js:5882 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined

Please advice me how to achieve this in an efficient way.

1 ответ

Решение

Вы не создаете productsмассив. Сделай это:

products: Products[] = [];
Другие вопросы по тегам