且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

RX JS过滤器方法不返回过滤器数组

更新时间:2023-02-16 21:14:08

因为这不是您应该在RxJS中使用Observables的方式.RxJS中的过滤器始终返回另一个Observable,并且从不直接对已处理的值进行赋值.

Because this is not how you're supposed to use Observables in RxJS. Filters in RxJS always return another Observables and never directly values the processed.

操作员 filter()希望您根据要包含还是排除布尔值,返回布尔值 true false .已处理的可观察流.由于您要使用

Operator filter() expects you to return boolean true or false based on whether you want to to include or exclude the item from the processed Observable stream. Since you're passing the entire array as a single value with Rx.Observable.of(items) it always passes everything or nothing (the returned array is converted into boolean).

因此,让我们使用 Observable.from 静态方法从可迭代对象创建一个Observable,它将数组中的每个项目作为单个值发出,然后只需 filter()即可排除所有不符合条件的项目与谓词不匹配.

So let's use Observable.from static method to create an Observable from an iterable that'll emit each item in the array as a single value and then just filter() to exclude all items that don't match the predicate.

const filterBy = {title: 'javascript'};
const items = [{title: 'javascript'}, {title: 'css'}, {title: 'html'}];

const observable = Rx.Observable.from(items).filter(item => {
    return item.title.indexOf(filterBy.title) !== -1;
});

observable.subscribe(f => console.log(f));