【问题标题】:Subscribe returns undefined variable订阅返回未定义的变量
【发布时间】:2020-08-12 23:53:33
【问题描述】:

所以一般来说,购物车的详细信息存储在本地存储中,被解析回来并分配到一个数组中,然后应该订阅并发布到 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');

    };

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]: 发送到客户端后无法设置标头

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

非常感谢!

【问题讨论】:

    标签: javascript angular local-storage subscribe


    【解决方案1】:

    我认为不接收来自执行CreateOrder() 的任何数据的原因是因为它得到了一个有趣的HTTP 错误。从关注这个document 我得到了这个内容,它说,

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

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

    【讨论】:

    • 嗨,标题的响应是:{message: "product not found"} message: "product not found",这是我后端的错误,但整个产品信息显示在“请求有效负载”,以及我为测试创建的标题..product-token: [{"_id":"5e5a6307d07a33280ce8c49c","product_Name":"GEL-Contend 5","product_Description":"Shoes 2", "product_Price":85,"product_Img":"../assets/shoes/asics-mens-gel-contend-5-running-shoes.JPG","id":13,"product_Quantity":1,"type" :"shoes"}] 引用者:localhost:4200/checkout
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2021-04-27
    • 2020-06-28
    • 1970-01-01
    • 2020-12-18
    • 2018-03-27
    相关资源
    最近更新 更多