NicoleZ
NicoleZ

Reputation: 1780

Filter Method Return Empty Array in Angular 6

I have created simple product component in Angular 6.When user click certain product category it filter those product to the user.

 subscriptionCat: Subscription;
 filterdProduct: any[];
 products: any[] = [];
 categories: any[];
 category: string;

ngOnInit() {

 this.productService.getAll().pipe(switchMap(prodData => {
   this.products = prodData;
   console.log(this.products);
   return this.route.queryParamMap
    })).subscribe(params => {
       this.category = params.get('category');
       this.filterdProduct = (this.category) ?
       this.products.filter(p => { p.category === this.category }) : this.products;
  });


 this.subscriptionCat = this.categoryService.getCategories()
 .subscribe(catData => {
   this.categories = catData;
  });

}

when i clicked on category in HTML template this.product.filter method return empty array. i checked the filter condition variables (p.category === this.category ) and it works fine.if there is no category to matched it should return default products array to the filterdProduct even thats not work at all.

Upvotes: 0

Views: 2573

Answers (2)

NicoleZ
NicoleZ

Reputation: 1780

Solution for this is remove the curly braces inside filter method because by default Javascript uses the curly braces as code block not as a object.

Upvotes: -1

andahan
andahan

Reputation: 713

The problem is the filter method is expecting a return value, and you’re not returning anything.

There are 2 ways you can fix this, both do the same thing.

filter(p => p.category === this.category)

or

filter(p => { return p.category === this.category; })

Upvotes: 4

Related Questions