【发布时间】:2020-08-28 05:21:05
【问题描述】:
我想在网上商店中按类别进行过滤。实际上我坚持使用 Mosh 的教程,因为我在浏览器或命令提示符中没有错误消息,但没有任何内容被过滤甚至显示。我是 Angular 和/或 typescript 的绝对初学者,所以请善待^^ 我试图自己解决这个问题已经很久了,但它不起作用。请帮帮我。
这是我的代码:
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>
【问题讨论】:
-
this.category 设置是否正确?你有控制台记录吗?
-
我在控制台记录了 this.category,它显示了正确的点击类别。你是这个意思吗?
标签: javascript angular typescript filter