【发布时间】:2019-03-14 13:41:49
【问题描述】:
我刚开始学习 RxJS。我尝试做的一件事没有太多运气,那就是弄清楚如何搜索/过滤主题,或者创建一个我可以搜索的观察数组。
我尝试过管道和过滤 Subject 和 BehaviorSubject,但谓词中的值是 RxJS 特定的。 从我在各种帖子中阅读的内容来看,方法是观察数组以使用主题。
我可以轻松拥有两个变量,一个数组和主题,然后搜索数组。但我想完成这个变量。
在 Knockout 中,可以搜索观察到的数组。
这在 RxJS 中可行吗?
提前致谢。
例子:
layers: Rx.Subject<any> = new Rx.Subject<any>();
toggleLayer (layerId, visible) {
//find layer we need to toggle
// How do I search the subject to get the values added in next()?
// tried from(this.layers), pipe does not fire
const source = of(this.layers);
const example = source.pipe(filter((val, index) => {
//val is subject, and only iterates once, even if more than one value in subject
// tslint:disable-next-line:no-debugger
debugger;
return false;
}));
const sub = example.subscribe((val) => {
// tslint:disable-next-line:no-debugger
debugger;
});
}
private addLayer = (layerName, layerObj, layerType) => {
// component class is subscribed to layers subject. Update UI when layer is added
this.layers.next({
layerId: this.layerId,
name: `${layerName}_${this.layerId}`,
layerObj: layerObj,
visible: true,
layerType: layerType
});
}
【问题讨论】:
-
不清楚您的意思,能否提供一些代码示例,其中包含您希望接收的输入和输出?
-
是的,但您必须搜索数组。例如
subject$.map(data => data.filter(...)) -
fromRxJS 函数接受一个数组作为输入,并返回一个 Observable,它为数组中包含的每个项目发出一次。因此,如果您真的想使用从数组开始的 Observable 进行搜索/过滤,您可以执行from(myArray).pipe(filter(item => item.foo = 'bar')) -
@OlesSavluk 我要做的是搜索主题。我们可以使用 next() 传入值,那么如何在主题内使用过滤器找到值?我想使用一个变量来做到这一点。我不想保留一个单独的数组来搜索。一个主题变量。就像淘汰赛一样。
-
@Picci 但问题是,我需要“观察”变化,因为我有一个组件类来监听该数组的变化,也就是主题。根据我的阅读,唯一的方法是使用主题,而不是来自(数组)的可观察对象
标签: javascript rxjs