【发布时间】:2020-09-22 06:09:40
【问题描述】:
我正在使用 rxjs 在 Angular App 中构建搜索和过滤系统。
我有以下几点:
interface User{ //exmaple model
_id: string;
name: string;
}
filters$ = new BehaviorSubject<Array<User>>([]);
search$ = new BehaviorSubject<Array<User>>([]);
// I use these two and merge them in another function as following
const myData$ = merge(this.search$.asObservable(), this.filters$.asObservable())
.pipe(distinctUntilChanged(distinctCheck))
使用实用函数distinctCheck 类似于:
const distinctKey = (elem) => {
if(elem === null){
return elem
}
if(this.hasId(elem)){
return elem["_id"];
}
if(this.hasName(elem)){
return elem["name"]
}
return this.createComparisonString(elem)
}
但这对我来说要么是一个可观察的,要么是另一个。所以我的问题是:
如何合并两个 observables 并只发出两个数组共有的值?有时 filters$ 可能会发出一个包含 30 个元素的数组。有时 search$ 可能会发出一个只有 2 个元素的数组?
IE:
如果filter$ 包含:
[{_id:'1', name:'jhon'},{_id:'2', name:'doe'},{_id:'3', name:'jolly'},{_id:'4', name:'some random dude'},{_id:'5', name:'some random other dude'},{_id:'6', name:'johny'},{_id:'7', name:'bravo'}]
而search$ 包含:
[{_id:'1', name:'jhon'},{_id:'101', name:'myDoe'},{_id:'301', name:'some-jolly'},{_id:'4', name:'some random dude'}, {_id:'7', name:'bravo'}]
我希望myData$ 发出类似:
[{_id:'1', name:'jhon'},{_id:'4', name:'some random dude'}, {_id:'7', name:'bravo'}]
谢谢大家! :)
【问题讨论】:
标签: angular typescript rxjs rxjs6