订阅返回未定义的变量

问题描述 投票:1回答:1

因此,购物车详细信息通常存储在本地存储中,被解析并分配给数组,然后应订阅并发布到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 herethis.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]:将标头发送到客户端后无法设置标头

((node:17548)UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头]

非常感谢!

javascript angular local-storage subscribe
1个回答
0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.