angular - 在数组流上使用 RxJS 过滤器操作符
问题描述
我想知道是否可以在数组流上进行操作(例如过滤),然后再次发出数组而不连接数组的元素或使用常规数组运算符。假设我有一个包含单个数组的可观察对象。然后我可以执行以下操作:
const MINWEIGHT = 15;
interface fruit {
name: string;
weight: number;
}
let apple: fruit = { name: "apple", weight: 2 };
let orange: fruit = { name: "orange", weight: 20 };
let fruitBasket1 = [apple, orange, orange];
let fruitBasket2 = [apple, apple, apple];
let sub = new Subject<fruit[]>();
sub
.asObservable()
.pipe(
concatMap(x => x),
filter(x => x.weight > MINWEIGHT),
toArray()
)
.subscribe(console.log); // result: [ orange, orange];
sub.next(fruitBasket1);
sub.complete();
如果sub.complete()
没有调用并且有多个fruit[] (e.g. fruitBasket2)
. observable 可以在([orange, orange], [orange])
不使用常规数组运算符的情况下发出两个数组吗?使用 map(RxJS) -> filter(array operator) 很容易,但我想知道是否只能使用 RxJS 运算符
解决方案
你可以试试这样的
sub
.asObservable()
.pipe(
concatMap(x =>
from(x).pipe(
filter(x => x.weight > MINWEIGHT),
toArray()
)
)
)
.subscribe(console.log);
关键思想是您通过from
运算符在流中转换源发出的每个数组,然后在与单个数组相关的单个流上应用 rxjsfilter
和toArray
逻辑。
推荐阅读
- javascript - Concat 2 输入值并将结果绑定到输入
- python - 按第一个字母字符的索引修剪字符串
- c# - 为什么 C# 针对 ushorts 上的模运算发出错误“无法隐式地将 int 转换为 ushort”?
- python - pandas 过滤是否支持别名?
- python - 检查字符串是否为回文返回错误结果
- javascript - 单击外部时如何关闭菜单?
- python - 为什么我的数组没有初始化?Numpy - 错误
- javascript - 为什么输入中的值没有加载来自 vuex 的值?
- ios - 应用程序在模拟器上完美运行,上传到 AppStore 后 - 找不到 pod
- java - 如何在 JFrame 中将绘制的内容居中?