我通过创建API并在角度2服务中调用它们来更新基于其在nodejs中的id的产品。
路由/ products.js
router.post('/:id', function(req, res, next) {
Products.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if(err){
res.json({success: false, msg:'Failed updating products'});
} else {
res.json({success: true, msg:'success updating products'});
}
});
});
这就是我在邮递员中传递的方式:POST请求
{
"id":"596df0ffcb429a586ef6c0bf",
"category_id": "596ddb165314d15618795826",
"product_name":"Laysssss masala",
"product_price":5,
"product_image":"image1ddd",
"product_desc":"Yummyddsd",
"product_status":"Activedddd"
}
产品似乎保存在数据库中。
当我在角度下调用服务并在浏览器中尝试时,我在broswer中获得“Product updated successfully”,但没有在DB中反映。
component.ts
onSaveConfirm(event) {
if (window.confirm('Are you sure you want to save?')) {
// var prodId = event.newData['_id']
//console.log(event.newData)
this.productService.productUpdate(event.newData).subscribe(data => {
if (data.success) {
console.log('Edited success')
this.flashMessage.show('Product updated successfully', { cssClass: 'alert-success', timeout: 3000 });
this.router.navigate(['/category-items']);
} else {
console.log('failure edited...')
this.flashMessage.show('Something went wrong', { cssClass: 'alert-danger', timeout: 3000 });
this.router.navigate(['/category-items']);
}
});
event.confirm.resolve(event.newData);
} else {
event.confirm.reject();
}
}
product.service.ts
productUpdate(products) {
var prodId = products['_id'];
console.log(products)
let prodUrl = "http://localhost:8080/products/" + prodId
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let prodIdObj = JSON.stringify({ products: products })
return this.http.post(prodUrl, prodIdObj, { headers: headers })
.map((response: Response) => response.json())
.do(data => JSON.stringify(data))
.catch(this.handleError);
}
答案 0 :(得分:0)
也许你的问题在这里:
在product.service.ts
:
productUpdate(products) {
//skipped
let prodUrl = "http://localhost:8080/products/" + prodId
//skipped
}
和products.js
router.post('/:id', function(req, res, next) {
Products.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if(err){
res.json({success: false, msg:'Failed updating products'});
} else {
res.json({success: true, msg:'success updating products'});
}
});
});
将其更改为:
router.post('products/:id', function(req, res, next) {
//do something
});