RX JS过滤器方法不返回过滤器数组 [英] Rx js filter method does not return the filter array

查看:79
本文介绍了RX JS过滤器方法不返回过滤器数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Array返回已过滤的可观察对象,但是当我订阅此可观察对象时,它不返回已过滤的数组,而是返回原始数组.为什么?

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

推荐答案

因为这不是您应该在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));

这篇关于RX JS过滤器方法不返回过滤器数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆