I am looking to retrieve objects asynchronously based on their category. In other words, I want my products to be loaded asynchronously by category.
Currently, I have a function named 'getProductByID' that searches for a product using its ID.
getProductByID(id: number): Observable<ProductModel> {
return of(ProductsList.find((product) => product.id === id));
} //this function works properly
//I attempted to create a similar function for categories,
//but I'm unsure how to match the category from the array
getProductsByCategory2(selectedCategory: CategoryModel): Observable<ProductModel[]> {
return of(ProductsList.find((product) => product.category === selectedCategory)
} //this approach is not successful
getProductsByCategory(selectedCategory: CategoryModel): ProductModel[] {
const products: ProductModel[] = [];
for (const product of ProductsList) {
for (const category of product.category) {
if (category === selectedCategory.id) {
products.push(product);
}
}
}
return products;
}// this function also works as expected, but does not provide asynchronous results
I need to identify all products that match with a specific category ID. Keep in mind that each product can have multiple categories assigned to it.