Rx js filter method does not return the filter array

半世苍凉 提交于 2019-12-12 04:28:19

问题


I want to return filtered observable from Array, but when I am subscribing to this observable it does not return the filtered array, it returns the original array. why?

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


const filtered = Rx.Observable.of(items).filter(i => {
  const filtered = i.filter(item => item.title.indexOf(filterBy.title) !== -1);
  console.log('filtered', filtered); // The array length is one
  return filtered;
})

filtered.subscribe(f => console.log(f) // The array length is three);

回答1:


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.

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

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



回答2:


You can return an array with the toArray opereator:

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;
}).toArray();


来源:https://stackoverflow.com/questions/40339798/rx-js-filter-method-does-not-return-the-filter-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!