Angular 2中的HTTP POST

时间:2017-09-10 06:19:17

标签: javascript json angular angular2-http

我在以角度2发布数据时遇到了问题。

postOrder() {

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let data=JSON.stringify({
                          customer_id: this.cusid,
                          mode_code: this.data2code,
                          order_totalpayment: this.dataprice,
                          order_status: this.status,
                          order_remarks: this.remarks,
                          order_type: this.ordertype
                        });


  this.http.post('http://JSON-API',data,headers)
  .map(res => res.json())
  .subscribe(res => {
  console.log("Success Order No.: "+res);
  this.ordernum = res;
  });

        let data2=JSON.stringify({
                        order_no: this.ordernum,
                        prod_id: this.dataid,
                            order_product_quantity: this.quantity,
                            order_subtotal: this.dataprice
                            });

  this.http.post('http://JSON-API',data2,headers)
  .map(response => response.json())
  .subscribe(response => {
  console.log("Order List No.: "+response);
  console.log(this.ordernum);
  });

}

我的问题是我无法发布res数据,但是当我使用控制台日志时,它会向我显示正确的数据。我所做的是将res数据传递给ordernum变量。

this.http.post('http://JSON-API',data,headers)
      .map(res => res.json())
      .subscribe(res => {
      console.log("Success Order No.: "+res);
      this.ordernum = res;
      });

然后我尝试POSTorder_no添加到我的JSON API。

let data2=JSON.stringify({
                        order_no: this.ordernum,
                        prod_id: this.dataid,
                            order_product_quantity: this.quantity,
                            order_subtotal: this.dataprice
                            });

正确的数据显示在控制台中,但在我的JSON API中,order_no始终为零。除了order_no.之外,我POST的所有数据都有效。我该怎么做才能解决这个问题。希望您能够帮助我。提前谢谢。

1 个答案:

答案 0 :(得分:1)

this.ordernum没有被定义,除非第一个http帖子被解析,把第二个http帖子放在subscribe函数中来拥有它:

 this.http.post('http://JSON-API',data,headers)
  .map(res => res.json())
  .subscribe(res => {
      console.log("Success Order No.: "+res);
      this.ordernum = res;
      let data2=JSON.stringify({
                        order_no: this.ordernum,
                        prod_id: this.dataid,
                            order_product_quantity: this.quantity,
                            order_subtotal: this.dataprice
                            });
      this.http.post('http://JSON-API',data2,headers)
      .map(response => response.json())
      .subscribe(response => {
          console.log("Order List No.: "+response);
          console.log(this.ordernum);
      });
  });