По сути, я хочу взять продукты из локального хранилища и вставить их в mongoDB.
Мой бэкэнд работает отлично. Схема заказа:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Order = new Schema ({
_id: mongoose.Schema.Types.ObjectId,
firstName: {type: String},
lastName: {type: String},
email: {type: String},
phone: {type: Number},
createdAt: {type: Date, default: Date.now},
address: {type: String},
productName: {type: String},
productDesc: {type: String},
productQuantity: {type: Number},
productPrice:{type: Number},
totalPrice:{type: Number},
},
{
collection: 'orders'
}
);
module.exports = mongoose.model('Order', Order);
Маршрут заказа:
//post order
orderRouter.route('/').post((req, res) =>{
const order = new Order({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
firstName:req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
phone: req.body.phone,
address: req.body.address,
productName: req.body.productName,
productDesc: req.body.productDesc,
productQuantity: req.body.productQuantity,
productPrice:req.body.productPrice,
totalPrice:req.body.totalPrice,
});
order.save()
.then(result => {
console.log(result);
return res.status(200).json({
message: "Order was Created",
order: {
_id: order._id,
firstName:order.firstName,
lastName: order.lastName,
email: order.email,
phone: order.phone,
address: order.address,
createdAt: new Date,
productName: order.productName,
productDesc: order.productName,
productQuantity: order.productQuantity,
productPrice: order.productPrice,
totalPrice: order.totalPrice
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error:err
});
});
});
товары сохраняются в локальном хранилище:
CheckoutForm. HTML (только поля корзины):
<div class="col-md-4 order-md-2 mb-4">
<h4 class="d-flex justify-content-between align-items-center mb-3">
<span class="text-muted">Your cart</span>
<span class="badge badge-secondary badge-pill">{{ productService.itemCount()}}</span>
</h4>
<ul class="list-group mb-1">
<li class="list-group-item d-flex justify-content-between lh-condensed" *ngFor = "let prod of productAddedToCart;">
<div class = form-group>
<h6 class="my-0" formControlName = "productName" ngDefaultControl name = "productName" #productName>{{prod.product_Name}}</h6>
<small class="text-muted" formControlName = "productQuantity" ngDefaultControl>Quantity: {{prod.product_Quantity}}</small><br>
</div>
<div class = "form-group">
<span class="text-muted" formControlName = "productPrice" ngDefaultControl>{{prod.product_Price * prod.product_Quantity | currency: '$'}}</span>
</div>
</li>
<div class = "form-group">
<li class="list-group-item d-flex justify-content-between">
<strong><span>Total (USD)</span></strong>
<strong formcontrolName = "totalPrice" ngDefaultControl>{{allTotal | currency: '$' }}</strong>
</li>
</div>
</ul>
CheckoutForm.TS:
constructor(private orderService:OrderService,private productService: ProductService, private fb: FormBuilder, private connectionService: ConnectionService, private router: Router) {
this.createForm();
}
createForm(){
this.checkOutForm = this.fb.group({
firstName : [null, Validators.required],
lastName : [null, Validators.required],
phone : [null, Validators.required],
email : [null, Validators.required],
address : [null, Validators.required],
country: [null, Validators.required],
city : [null, Validators.required],
nameOnCard : [null, Validators.required],
creditCardNumber: [null, Validators.required],
exp: [null, Validators.required],
cvv: [null, Validators.required],
message: [''],
contactFormCopy: [''],
productName: [Validators.required],
ProductDesc: [Validators.required],
productQuantity: [Validators.required],
productPrice: [Validators.required],
totalPrice: [Validators.required]
});
}
onSubmit() {
this.connectionService.sendReceipt(this.checkOutForm.value).subscribe(() => {
alert('Your order has been received.');
this.orderService.CreateOrder(this.checkOutForm.value).subscribe((data:Order) => {
this.order = data
console.log(this.order);
});
this.checkOutForm.reset();
this.disabledSubmitButton = true;
this.router.navigate(['/']);
localStorage.removeItem('product');
localStorage.removeItem('cartItemCount');
}, error => {
console.log('Error', error);
});
}
В MongoDB:
Как видите, только поля с 'Input' и 'formControlName' сохраняются в базе данных, и я понимаю, что 'formContolName' должен находиться внутри поля 'Input'.
Поэтому мой вопрос заключается в том, как мне взять данные о продукте из локального хранилища и назначить их в соответствующие поля в файле HTML?
Оценили!