我们是 Angular 和构建 LMS 应用程序的新手,需要按名称从一个类别中获取所有产品。我们在后端和角度前端有示例代码,如下所示
连接mysql的后端product.js文件
router.get('/category/:catName', (req, res) => { // Sending Page Query Parameter is mandatory
http://localhost:3636/api/products/category/categoryName?page=1
let page = (req.query.page !== undefined && req.query.page !== 0) ? req.query.page : 1; //
check if page query param is defined or not
const limit = (req.query.limit !== undefined && req.query.limit !== 0) ? req.query.limit : 10;
// set limit of items per page
let startValue;
let endValue;
if (page > 0) {
startValue = (page * limit) - limit; // 0, 10, 20, 30
endValue = page * limit; // 10, 20, 30, 40
} else {
startValue = 0;
endValue = 10;
}
// Get category title value from param
const cat_title = req.params.catName;
database.table('products as p')
.join([
{
table: "categories as c",
on: `c.id = p.cat_id WHERE c.title LIKE '%${cat_title}%'`
}
])
.withFields(['c.title as category',
'p.title as name',
'p.price',
'p.quantity',
'p.description',
'p.image',
'p.id'
])
.slice(startValue, endValue)
.sort({id: 1})
.getAll()
.then(prods => {
if (prods.length > 0) {
res.status(200).json({
count: prods.length,
products: prods
});
} else {
res.json({message: `No products found matching the category ${cat_title}`});
}
}).catch(err => res.json(err));
});
我们在 product.service.ts 中有示例代码,如下所示
getProductsFromCategory(catName: String): Observable<ProductModelServer[]> {
return this.http.get<ProductModelServer[]>(this.url + 'products/category/' + catName);
}
我们在 product.model.ts 中有如下代码
export interface ProductModelServer {
id: Number;
name: String;
category: String;
description: String;
image: String;
price: Number;
quantity: Number;
images: String;
}
export interface serverResponse {
count: number;
products: ProductModelServer[]
};
我们想在 home.component 页面中调用 getProductsFromCategory 并仅显示一个类别的产品。需要代码如何从一个类别中获取产品显示,例如“教程”
我们尝试了下面的代码,但显示错误提示找不到名称 Tutorial。
ngOnInit() {
this.productService.getProductsFromCategory(Tutorial).subscribe((prods:ProductModelServer[] )
=> {
this.products = prods.products;
console.log(this.products);
});
}