Angular FilterIngredientsPipe问题:多不含成分筛选失效,单筛选正常
Fixing the Multi-Ingredient Exclusion Filter in Angular Pipe
I see exactly where the issue is—your current logic checks if any of the excluded ingredients are missing from a product, but what you actually need is to ensure all selected excluded ingredients are absent from the product. Let's break this down and fix it.
The Problem with Your Current Code
This line is the culprit when multiple ingredients are selected:
activeIngrs.find(ai => product.filters.ingredients.some(a => a.id !== ai.id)) || product.filters.ingredients.length === 0
product.filters.ingredients.some(a => a.id !== ai.id)will almost always returntrueunless the product only contains that single excluded ingredient.activeIngrs.find(...)returns the first excluded ingredient that meets the above condition, so even if one excluded ingredient is missing (but others are present in the product), the product gets incorrectly kept.
The Correct Logic
You want to retain products that do NOT contain any of the selected excluded ingredients. To implement this cumulative exclusion:
- Check every selected excluded ingredient
- Verify that none of them exist in the product's ingredient list
- Only keep the product if all excluded ingredients pass this check
Updated Pipe Code
Here's the fixed FilterIngredientsPipe with the corrected logic:
import { Pipe, PipeTransform } from '@angular/core'; import { Product } from '../../models/product'; import { GenericFilter } from '../../store/states/results-filters-state'; @Pipe({ name: 'filterIngredients' }) export class FilterIngredientsPipe implements PipeTransform { transform(value: Product[] = [], ingrs: GenericFilter[] = []): Product[] { const activeIngrs = ingrs.filter((ingr: GenericFilter) => ingr.selected); if (!activeIngrs.length) { return value; } // Keep products that have none of the active excluded ingredients return value.filter((product: Product) => activeIngrs.every(ai => !product.filters.ingredients.some(a => a.id === ai.id) ) ); } }
Key Changes Explained
activeIngrs.every(...): This method ensures we validate all selected excluded ingredients. The product is only kept if the callback returnstruefor every element inactiveIngrs.!product.filters.ingredients.some(a => a.id === ai.id): This checks if the product does NOT contain the current excluded ingredient. For products with no ingredients at all,some()returnsfalse, so!falseevaluates totrue—which is correct, since a product with no ingredients can't contain any excluded ones.
Your existing template code doesn't need any adjustments—it will work as intended with this updated pipe.
内容的提问来源于stack exchange,提问作者cerealex
相关产品推荐
相关产品推荐

