订阅返回未定义的变量

时间:2020-04-29 01:07:16

标签: javascript angular local-storage subscribe

因此,通常,购物车详细信息存储在本地存储中,被解析并分配给数组,然后应订阅并发布到MongoDB,但返回“未定义”:

checkout.ts

confirmOrder(){
    let orderDetails: any = {};
    orderDetails.firstName = this.checkOutForm.controls['firstName'].value;
    orderDetails.lastName = this.checkOutForm.controls['lastName'].value;
    orderDetails.phone = this.checkOutForm.controls['phone'].value;
    orderDetails.address = this.checkOutForm.controls['address'].value;
    orderDetails.country = this.checkOutForm.controls['country'].value;
    orderDetails.city = this.checkOutForm.controls['city'].value;

    this.orderItem=[];
    for (let i in this.productAddedToCart) {
      this.orderItem.push({

        product_Name:this.productAddedToCart[i].product_Name,
        id:this.productAddedToCart[i].id,
        product_Price:this.productAddedToCart[i].product_Price,
        product_Quantity:this.productAddedToCart[i].product_Price,
        type:this.productAddedToCart[i].type,
        product_Img: this.productAddedToCart[i].product_Img,
        product_Description:this.productAddedToCart[i].product_Description,
       _id:this.productAddedToCart[i]._id
  
      });
   }
    orderDetails.product= this.orderItem
    debugger
    console.log("orderDetails:", orderDetails.product)

    this.connectionService.sendReceipt(this.checkOutForm.value).subscribe((res) =>{
      debugger
      console.log("res is:", res);
    });
  
    this.orderService.CreateOrder(orderDetails).subscribe((data:OrderDetails) => {
      debugger
      console.log("data is:", data) // prints nothing
      debugger
      this.globalResponse = data 
      console.log("data is:", this.globalResponse) //prints nothing
 
      debugger
    });
      alert('Your order has been received.');
      this.checkOutForm.reset();
      this.disabledSubmitButton = true;
      this.router.navigate(['/']);
      localStorage.removeItem('product');
      localStorage.removeItem('cartItemCount');

    };

enter image description here

enter image description here this.globalResonse是“未定义”。 为什么无法console.log(data)? 不会订阅吗?

order.service.ts:

  CreateOrder(orderDetails:OrderDetails){
    return this.http.post(`${this.uri}/order`, orderDetails,{
    observe:'body'})
  }

如果需要,我的后端(可以):

//create order
orderRoute.route('/').post((req, res) =>{
    Product.findById(req.body.productId)
    .populate('product')
    .then(product => {
        if(!product){
            return res.status(404).json({
                message: "product not found"
            });
        }
        const order = new OrderDetails({
            _id: new mongoose.Types.ObjectId(),
            product: req.body.productId,
            email: req.body.email,
            firstName:req.body.firstName,
            lastName: req.body.lastName,
            phone: req.body.phone,
            address: req.body.address,
        });
        return order.save()
        })
        
        .then(result => {
            console.log(result);
            
            return res.status(200).json({
                
                message: "Order was Created",
                
                order: {
                    order_id: result._id,
                    product: result.product,
                    firstName:result.firstName,
                    lastName: result.lastName,
                    email: result.email,
                    phone: result.phone,
                    address: result.address,
                    createdAt: new Date,
                },
                request:{
                    type:"GET",
                    order_url: "http://localhost:5000/order/" + result._id
                }
            });
        })
        .catch(err => {
            console.log(err);
            res.status(500).json({
                error:err
            });
        });
    
    });    

我还收到2个错误: 错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头

(节点:17548)UnhandledPromiseRejection警告:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头

非常感谢!

1 个答案:

答案 0 :(得分:0)

我认为之所以不能从执行CreateOrder()中接收任何数据,是因为它收到了一个有趣的 HTTP 错误。通过关注此document,我得到了该内容,并说,

错误[ERR_HTTP_HEADERS_SENT]是一个有趣的错误,当服务器尝试向客户端发送多个响应时会触发该错误。这意味着对于给定的客户端请求,服务器先前已向客户端发送了响应(请求资源的成功响应或错误请求的错误响应),现在却意外地尝试发送另一个响应

因此您的后端尝试发送两次响应。这就是这里的问题。如果可以在浏览器控制台中打开“网络”选项卡,则可以检查其是否正确。
希望这会有所帮助。