简体   繁体   English

RxJS filter()运算符

[英]RxJS filter() operator

I am trying to find the cleanest solution to use filter() operator in order to filter my observables. 我正在尝试找到最干净的解决方案以使用filter()运算符来过滤我的可观察对象。

Here I am replicating the service call to get a femaleList separately 在这里,我复制服务调用以单独获取一个femaleList

export class MyComp implements OnInit {

    maleList: IContact[] = [];
    femaleList: IContact[] = [];    

    constructor(private _contactService: ContactService) { }
    ngOnInit() : void {
        this._contactService.getContacts()
         .filter(male => male.gender === 'M')
        subscribe(maleList => this.maleList = maleList);

        this._contactService.getContacts()
         .filter(female => female.gender === 'F')
        subscribe(femaleList => this.femaleList = femaleList);
     } }

Contactlist 联系人列表

 [{
      "id" : 1,
      "name" : "Todd",
      "gender" : "M"
    }, {
      "id" : 2,
      "name" : "Lillian",
      "gender" : "F"
    }]

Is there any option in RxJS operators with single observable to assign to two variables. RxJS运算符中是否有任何可观察的选项分配给两个变量。

How can i filter the Contacts and assign it to maleList and femaleList using RxJS filter() operator. 如何使用RxJS filter()运算符过滤联系人并将其分配给maleListfemaleList

Thanks in advance 提前致谢

You don't need a filter: 您不需要过滤器:

this._contactService.getContacts()
  .subscribe(person => {
    if(person.gender === 'F'){
      this.femaleList.push(person);
    } else {
      this.maleList.push(person);
    }

If you want to use a single Observable and subscribe to it with two different Observers you'll need to use share() or shareReplay() (which is in RxJS 5 now available only with .publishReplay().refCount() ) (See https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/publish.md and https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/sharereplay.md ). 如果要使用单个Observable并使用两个不同的Observer进行订阅,则需要使用share()shareReplay() (在RxJS 5中,现在仅可用于.publishReplay().refCount() )(请参见) https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/publish.mdhttps://github.com/Reactive-Extensions/RxJS/blob/master/doc/ api / core / operators / sharereplay.md )。

let data = [{
    "id" : 1,
    "name" : "Todd",
    "gender" : "M"
}, {
    "id" : 2,
    "name" : "Lillian",
    "gender" : "F"
}];

let maleList = [];
let femaleList = [];

let source = Observable.defer(() => {
        console.log('Observable.defer');
        return Observable.from(data);
    })
    .publishReplay()
    .refCount();

source
    .filter(male => male.gender === 'M')
    .toArray()
    .subscribe(list => maleList = list);

source
    .filter(male => male.gender === 'F')
    .toArray()
    .subscribe(list => femaleList = list);

console.log('maleList', maleList);
console.log('femaleList', femaleList);

See live demo: https://jsbin.com/hapofu/edit?js,console 观看现场演示: https : //jsbin.com/hapofu/edit?js,console

This prints to console: 打印到控制台:

Observable.defer
maleList [ { id: 1, name: 'Todd', gender: 'M' } ]
femaleList [ { id: 2, name: 'Lillian', gender: 'F' } ]

Both these subscribers share the same connection to source and at the same time the response is "replayed" (if you subscribe after it was first emitted it'll reemitted without subscribing to the source again). 这两个订户共享与source的相同连接,并且同时“重放”响应(如果您在第一次发出响应后订阅,则将其重新发送而无需再次订阅source )。

Note that the items from filter() are emitted one at the time. 请注意, filter()中的项一次被发出。 That's why I used toArray() to collect all values and reemit them as a single array. 这就是为什么我使用toArray()收集所有值并将其重新发送为单个数组的原因。 Alternatively I could call eg. 另外,我可以打电话给。 maleList.push() with every value. maleList.push()具有每个值。

Btw, there's also partition() operator that you could use instead of filter() to avoid creating two subscriptions. 顺便说一句,您还可以使用partition()运算符代替filter()来避免创建两个订阅。

You could use lodash: 您可以使用lodash:

.partition(collection, [predicate= .identity]); .partition(collection,[predicate = .identity]);

https://lodash.com/docs/#partition https://lodash.com/docs/#partition

This returns 2 arrays, one where the values evaluate to false & the other to true. 这将返回2个数组,其中一个值的值为false,另一个值为true。 Just use 'gender' to build the evaluation. 只需使用“性别”即可建立评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM