How to Filter Items By Category, queryParams in Angular 2 or 4

Viewed 6821

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

1 Answers
Related