Having trouble filtering categories in a Webshop? I've been following a tutorial by Mosh but I can't seem to get it right. No error messages but nothing is being filtered or displayed. I'm brand new to Angular and/or typescript, so please be patient with me. I've tried to fix this on my own for ages with no luck. Can anyone help me out?
Here's the code I have:
products.component.ts:
export class ProductsComponent {
products: Product[]= [];
filteredProducts: Product[] = [];
categories$: Observable<any>;
category: string;
products$: Observable<any>;
constructor(
route: ActivatedRoute,
productService: ProductService,
categoryService: CategoryService) {
this.filteredProducts;
productService.getAll().subscribe (products => this.products);
//Shows Categories in View
this.categories$ = categoryService.getAll();
route.queryParamMap.subscribe(params => {
this.category = params.get('category');
this.categories$.subscribe(res => console.log (res)); //Console.log 5 Categories Observable
//Setting the filtered Products Array
this.filteredProducts = (this.category) ?
this.products.filter(p => {
return p.category === this.category;
}) :
this.products;
console.log(this.filteredProducts); // Console.log FilteredProducts Array
});
}
}
products.component.html:
<div class="row">
<div class="col-3">
<div class="list-group">
<!-- Bei queryParams c.name auswählbare Kategorien / bei c.key nicht sowie bei c.$key nicht-->
<a *ngFor="let c of categories$ | async "
routerLink= "/"
[queryParams]="{ category: c.name }"
class="list-group-item list-group-item-action"
[class.active]="category === c.name">
{{ c.name }}
</a>
</div>
</div>
<div class="col-9">
<div class="row">
<ng-container *ngFor="let product of filteredProducts ; let i = index">
<div class="col">
<div class="card" style="width: 15rem;">
<img [src]="product.imageUrl" class="card-img-top" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ product.title }}</h5>
<p class="card-text">{{ product.price | currency: 'EUR' }}</p>
<a href="#" class="btn btn-primary">Add to Cart</a>
</div>
</div>
</div>
<div *ngIf="(i + 1) % 2 === 0" class="w-100"></div>
</ng-container>
</div>
</div>
</div>