RxJs唯一地合并两个可观察对象

问题描述 投票:0回答:1

我正在使用rxjs在有角度的应用程序中构建搜索和过滤系统。

我有以下内容:

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

但是这使我可以观察到另一个。所以我的问题是:

如何合并两个可观察对象,并仅发出两个数组共有的值?有时候filter $可能会发出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
1个回答
0
投票

类似这样的方法应该起作用:

const filters$ = new BehaviorSubject<Array<{ id: string }>>([]);
const search$ = new BehaviorSubject<Array<{ id: string }>>([]);

const combinedAndFiltered$ = combineLatest(filters$, search$)
    .pipe(map(([filters, searches]) => {
        return filters.filter(filter => !!searches.find(search => search.id === filter.id));
    }));

combinedAndFiltered$.subscribe(console.log)

0
投票

compare运算符的distinctUntilChanged函数用于判断先前的发射是否不同于当前的发射。


0
投票

您实际上可以使用普通的Javascript实现。

© www.soinside.com 2019 - 2024. All rights reserved.