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

不羁的心 提交于 2019-12-04 11:39:59

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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!