【问题标题】:Filter Method Return Empty Array in Angular 6Angular 6中的过滤方法返回空数组
【发布时间】:2018-08-30 19:21:49
【问题描述】:

我在 Angular 6 中创建了简单的产品组件。当用户单击某个产品类别时,它会将这些产品过滤给用户。

 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;
  });

}

当我单击 HTML 模板中的类别时,this.product.filter 方法返回空数组。我检查了过滤条件变量(p.category === this.category),它工作正常。如果没有匹配的类别,它应该将默认产品数组返回给 filterdProduct,即使那根本不起作用。

【问题讨论】:

    标签: angular typescript angular6


    【解决方案1】:

    问题是过滤器方法需要一个返回值,而你没有返回任何东西。

    有两种方法可以解决这个问题,两者都做同样的事情。

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

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

    【讨论】:

      【解决方案2】:

      解决方案是删除 filter 方法中的大括号,因为默认情况下 Javascript 使用大括号作为代码块而不是对象。

      【讨论】:

        猜你喜欢
        • 2021-05-06
        • 2020-06-10
        • 2023-01-25
        • 1970-01-01
        • 2021-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多