【问题标题】:Sending cart data to server using Angular使用 Angular 将购物车数据发送到服务器
【发布时间】:2023-03-26 10:35:01
【问题描述】:

我正在建立一个电子商务网站。我想在结帐时发送订单数据,但我无法制作订单数据。需要帮助

我在下面静态发送。它正在工作,但我怎样才能通过 this.mycart 对象的迭代使其动态化

const body = new HttpParams()
.set('user_id', user_id)
.set('address_id', '89')
.set('final_price', this.grandtotal)
.set('payment_method', 'cod')
.set('txnid', '')
.set('payment_status', '0')
.set('slot_time', '12pm to 2pm')
.set('product_id[0]', this.mycart[0].id)
.set('product_name[0]', this.mycart[0].name)
.set('product_price[0]', this.mycart[0].price)
.set('quantity[0]', this.mycart[0].quantity)
.set('product_unit[0]', this.mycart[0].value)
.set('product_id[1]', this.mycart[1].id)
.set('product_name[1]', this.mycart[1].name)
.set('product_price[1]', this.mycart[1].price)
.set('quantity[1]', this.mycart[1].quantity)
.set('product_unit[1]', this.mycart[1].value);
      
 return this.httpClient.post(this.REST_API_SERVER+'user/place_order2', body.toString(), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
 });

【问题讨论】:

  • 请您添加更多信息。显示您的this.mycart object 的样子。

标签: post e-commerce ionic5 angular11


【解决方案1】:

我从我的一位资深人士那里得到了这个可行的解决方案

/* 创建购物车数组 */

const cartLoop = (httpBody, index, cartItems) => {

        httpBody['product_id['+index+']'] = cartItems.id;
        httpBody['product_name['+index+']'] = cartItems.name;
        httpBody['product_price['+index+']'] = cartItems.price;
        httpBody['quantity['+index+']'] = cartItems.quantity;
        httpBody['product_unit['+index+']'] = cartItems.value;
        
        return httpBody;
      }
      
      let cartData = {
        'user_id' : user_id,
        'address_id' : extraData.address_id,
        'final_price': this.grandtotal,
        'payment_method': extraData.payment_method,
        'txnid': extraData.payment_method,
        'payment_status': extraData.txnid,
        'slot_time': extraData.slot_time
      }

        for(var i=0; i<this.mycart.length; i++)
        {
          const cartItems = this.mycart[i];
          cartData = cartLoop(cartData, i, cartItems);
        }

        let body = new HttpParams({
          fromObject : cartData
        })

      return this.httpClient.post(this.REST_API_SERVER+'user/place_order2', body.toString(), {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      })

【讨论】:

  • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。