Angular 如何通过rxjs选择的动态过滤器过滤阵列
我这里有一系列的产品Angular 如何通过rxjs选择的动态过滤器过滤阵列,angular,rxjs,Angular,Rxjs,我这里有一系列的产品 let products=[ {id:1,category:[23,34],subcategory:[45,67],company:[56,78]} {id:2,category:[46,19],subcategory:[89,645],company:[16,88]} ] 这是我必须应用的动态过滤器数组 let filter=[ {key:"category",values:[19]} {key:"
let products=[
{id:1,category:[23,34],subcategory:[45,67],company:[56,78]}
{id:2,category:[46,19],subcategory:[89,645],company:[16,88]}
]
这是我必须应用的动态过滤器数组
let filter=[
{key:"category",values:[19]}
{key:"company",values:[88,16]}
]
如何通过rxjs
这是我的代码,它只适用于一个过滤器,但我需要动态地超过1
这是我给出的1个过滤器的代码,例如
type="category"
values=[18,19]
products.pipe(
flatMap(response => response),
filter(
(product: any) => {
return product[type].find((catnum) => values.includes(catnum))
}
), toArray()
).subscribe(data => {}
如果我正确理解了您的意思,您希望使用以下方法过滤产品数组:过滤器数组中的某些条件匹配,并且此过滤器数组可能会随时间而变化
首先,您应该使用map操作符来修改产品流。在map操作符中,您必须过滤通过条件的产品
this.products$
.pipe(
map((products) => {
return products.filter((product) => {
return this.filters.some((filter) => this.isProductMeetFilterConditions(product, filter))
})
})
)
private isProductMeetFilterConditions(product: Product, filter: Filter): boolean {
return filter.values.some((value) => {
return product[filter.key].includes(value)
})
}
我已经实现了它,您可以打开控制台并查看筛选结果,因此产品是多个产品的流,而不是产品阵列的流。过滤器呢?它也是一个过滤器条目流吗?它是一个过滤器数组的流还是一个普通对象?它工作正常,但是如果一个过滤器中的任何一个匹配,它的返回产品,如果不应该返回产品,如果任何过滤器不匹配,我在您的代码和它的返回产品[{key:“category”,values:[19]},{key:“company”,values:[18]}上尝试了这一点;如果产品满足所有过滤器,则只需将this.filters.some更改为this.filters.every