How can I get filter by category to work on an Angular component with a list of Products? Here's what my product model looks like:
export interface Product {
id: number;
categoryId: number;
}
Getting products from the service looks like this:
// Products from the API
getProducts(categoryId?: number): void {
if (categoryId) {
this.productService.getProducts()
.then(products => this.products = products);
this.products.filter((product: Product) => {
product.categoryId === categoryId;
});
} else {
this.productService.getProducts()
.then(products => this.products = products);
}
}
And Query Params is written like this:
filterProducts(category: Category) {
this.router.navigate(['/search'],
{queryParams: { category: category.id } });
}
in url I got this result - search?category=2
After the url is updated with the category id, the product list still returns all the list of items, it does not return only the products with category id of 2.
<ul class="dropdown-menu dropdown-menu-right">
<li *ngFor="let category of categories">
<a (click)="filterProducts(category)">
{{ category.name }}
</a>
</li>
</ul>
What do i need to do/add/implement or improve to make the changes in the url (query params), reflect in the list of products? Here's the link to the page i am working on for better understanding of the problem - https://deaninfotech.herokuapp.com/dashboard/ng/search
You'll need to subscribe to changes in your queryParams
, and run getProducts()
on that subscription. Something like the following, in the same component as getProducts
:
import { ActivatedRoute } from '@angular/router';
//...
@Component({
//...
})
export class SomeComponent {
constructor(
private activatedRoute: ActivatedRoute
) {
this.activatedRoute.queryParams.subscribe(params => {
this.getProducts(Number(params['category']));
});
}
//getProducts() {}
}
Edit to getProducts
, per comments.
You're getting cannot read "filter" of undefined
since you're setting this.products
after the promise asynchronously, which is correct, but your filter function is not within that async call. Adjust as follows, which should allow you to keep the function above in your constructor.
// Products from the API
getProducts(categoryId?: number): void {
if (categoryId) {
this.productService.getProducts()
.then(products => {
this.products = products.filter((product: Product) => product.categoryId === categoryId);
});
} else {
this.productService.getProducts()
.then(products => this.products = products);
}
}
来源:https://stackoverflow.com/questions/46185327/how-to-filter-items-by-category-queryparams-in-angular-2-or-4