We are new to angular and building a LMS app and need to get all products from one category by name. We have sample code in backend and angular frontend as below
Backend product.js file connecting to mysql
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));
});
We have sample code in product.service.ts as below
getProductsFromCategory(catName: String): Observable<ProductModelServer[]> {
return this.http.get<ProductModelServer[]>(this.url + 'products/category/' + catName);
}
We have code in product.model.ts as below
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[]
};
We want to call the getProductsFromCategory in our home.component page and display products from only one category. Would need the code how to get the product display from one category say "Tutorial"
We tried below code but showing error saying not able to find the name Tutorial.
ngOnInit() {
this.productService.getProductsFromCategory(Tutorial).subscribe((prods:ProductModelServer[] )
=> {
this.products = prods.products;
console.log(this.products);
});
}