问题描述
我现在已经根据某种逻辑从大型FormGroup中滤除了几个FormControl,我想知道如何合并/组合那些选定的FormControl,并且只有一个订阅..
I have filtered out few FormControl(s) from a large FormGroup based on some logic now - I'd like to know how can I merge / combine those selected FormControls and have only one subscribe..
我查看了RxJS文档和大理石图,但对它的理解不正确.理解所有这些并知道要为我的案例使用哪一个是非常令人困惑的:
I looked into RxJS docs and marble diagrams but didn't understand it properly. It's very confusing to understand all of these and know which one to use for my case:
- forkJoin
- combineLatest
- merge
- join
- zip
以下是有关该问题的详细信息:
Here's more detailed info about the question:
让我们说2个FormControls(即controlA,controlB).每当任何FormControl值更改时,我都想执行一些handlerFunction
.*每当任何控件值更改时,都需要执行一次我的handlerFunction(在我的情况下,一次更改任何一个控件)
Let's say 2 FormControls (i.e., controlA, controlB). I want to execute my some handlerFunction
whenever any of the FormControl value changes.* It needs to execute my handlerFunction once whenever any control valueChanges (In my case any one control will be changed at one time)
谢谢.
推荐答案
对您而言,最好的选择是combineLatest
,它在所有源Observable都发出至少一个值之后,然后在任何源Observable的每次发出之后发出:
The best option for you is combineLatest
that emits after all source Observables emitted at least one value and then on every emission from any source Observable:
Observable.combineLatest(controlA.valueChanges, controlB.valueChanges)
.subscribe(...);
最终,您可以将每个源与startWith(null)
链接在一起,以确保每个源都将立即发出一个项目并过滤订户中想要的内容.
Eventually you can chain each source with startWith(null)
to guarantee that every source will emit one item immediately and filter what you want in the subscriber.
Observable.combineLatest(
controlA.valueChanges.startWith(null),
controlB.valueChanges.startWith(null)
)
.subscribe(([val1, val2]) => ...);
顺便说一句,关于其他运算符:
Btw, about the other operators:
-
zip
-仅在所有来源发出相同数量的物品时发出 -
forkJoin
-当所有来源发出至少一项并完成时发出(valueChanges
从未发生) -
merge
-只是合并Observables,但您不知道哪一个发出了什么值 -
join
-我认为这不是RxJS 5的一部分
zip
- emits only when all sources emitted the same number of itemsforkJoin
- emits when all sources emitted at least one item and completed (never happens withvalueChanges
)merge
- just merges Observables but you can't know which one emitted what valuejoin
- I don't think that's part RxJS 5
这篇关于一次只能订阅多个FormControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!