首页 > 解决方案 > Angular 5 - 将项目动态添加到数组

问题描述

我有这两个功能:

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

标签: arraysangular5push

解决方案


我设法通过以下方式解决了我需要的问题:

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

推荐阅读