Angular 5 - 动态添加项目到数组

Angular 5 - Dynamically add items to an array

我有这两个功能:

cart()这是一个数组对象(这个信息是静态的)

cartItems这是一个数组对象(这个信息是动态的)

购物车 中可以有多个 cartItems。我如何将不同的商品放入购物车,这样我的最终结果将如下所示:

JSON:

"cart": [
            {
                "id": "1",
                "cartItem": [
                    {
                        "id": "cart Item 1",
                        "action": "New",
                        "quantity": 1,
                    },
                    {
                        "id": "cart Item 2",
                        "action": "New",
                        "quantity": 1,
                    }
            }
            ]

函数:

private cart(): CaCartItemsModel{
    return new CaCartItemsModel(
      "1",
      "Cambio",
      "TV"
);

private cartItems(): CaCartItemModel{
    return new CaCartItemModel(
      "cart Item 1/cart Item 2",
      "New",
      1
    );
  }

我设法通过以下方式解决了我的需求:

private createCartItems(cancellationModel: CancellationModel) {

    this.request.caAcProductOrderModel.caCartItems.getAllCartItems()
      .push(this.setCartItems());

    cancellationModel.channels.forEach(channel => {
      this.request.caAcProductOrderModel.caCartItems.getAllCartItems()
        .forEach(caCartItem => {
          caCartItem.caCartItem.getAllCartItem()
            .push(this.setCaCartItemModel(
              channel.id,
              channel.action,
              channel.name,
              "",
              true
            ));

          caCartItem.caCartItem.getAllCartItem()
            .forEach(cartItem => {
              cartItem.caProduct.caProductRelationship.getAllCaProductRelationship()
                .push(this.setCaProductRelationshipModel(channel.type));
              cartItem.caProductOffering.caCategory.getAllCategories()
                .push(this.setCaCategoryModel("promo"));
              cartItem.caProductOffering.caAttributes.getAllAttributes()
                .push(this.setCaAttributesModel("Numero fijo Asociado", this.activeCustomerServiceProvider.getPhoneNumber()));
              cartItem.cartItemRelationship.getAllCartItemRelationship()
                .push(this.setCaCartItemRelationshipModel(channel.id, "reliesOn"));
            });
        });
    });
}