按名称按角度获取一个类别中的所有产品



我们是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,并只显示一个类别中的产品。将需要如何从一个类别中获得产品展示的代码,例如";教程">

我们尝试了下面的代码,但显示错误,说找不到教程的名称。

ngOnInit() {
this.productService.getProductsFromCategory(Tutorial).subscribe((prods:ProductModelServer[] ) 
=> {
this.products = prods.products;
console.log(this.products);
});
}

您的getProductsFromCategory((方法接受String,所以像一样更新您的调用

"通过教程"&";。

ngOnInit() {
this.productService.getProductsFromCategory("Tutorial").subscribe((prods:ProductModelServer[] ) 
=> {
this.products = prods.products;
console.log(this.products);
});
}

相关内容

  • 没有找到相关文章

最新更新