combineLatest与FormControl valueChanges事件绑定不发出

New*_*iie 5 subscribe rxjs typescript angular

我通过2 [formControl]"toppings"收听2个表单:array和"toppings2":array.

我必须同时拥有表格的2个值.所以我把我的两个观察者与"CombineLatest"结合起来

我的代码:

ngOnInit() {
combineLatest(this.toppings.valueChanges, this.toppings2.valueChanges)
    .subscribe(val => console.log(val)) 
}
Run Code Online (Sandbox Code Playgroud)

但是现在,在组件的初始化中,只有一个表单发送console.log(val).

如果我在收到第二张表格的日志后点击此表格.你遇到这个问题吗?

ggr*_*nig 13

您可能希望两个Observable都有一个初始值.combineLatest只有在所有Observable都发出至少一个值时才会发出.使用startWith运算符创建此行为,如下所示:

combineLatest(
    this.toppings.valueChanges.pipe(startWith("")), 
    this.toppings2.valueChanges.pipe(startWith("")))
Run Code Online (Sandbox Code Playgroud)

或者,如果您有可用的初始值,则建议:

combineLatest(
    this.toppings.valueChanges.pipe(startWith(this.toppings.value)), 
    this.toppings2.valueChanges.pipe(startWith(this.toppings2.value)))
Run Code Online (Sandbox Code Playgroud)

请注意,这将使用初始值发出一次.要抑制此行为,您可以使用skip(1)运算符忽略此初始通知.

  • 或者 `şstartWith(this.toppings.value)`。 (2认同)