combineLatest与FormControl valueChanges事件绑定不发出

问题描述 投票:5回答:1

我通过2 [formControl]“toppings”收听2个表单:array和“toppings2”:array。

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

我的代码:

ngOnInit() {
combineLatest(this.toppings.valueChanges, this.toppings2.valueChanges)
    .subscribe(val => console.log(val)) 
}

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

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

angular typescript rxjs subscribe
1个回答
11
投票

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

combineLatest(
    this.toppings.valueChanges.pipe(startWith("")), 
    this.toppings2.valueChanges.pipe(startWith("")))

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

combineLatest(
    this.toppings.valueChanges.pipe(startWith(this.toppings.value)), 
    this.toppings2.valueChanges.pipe(startWith(this.toppings2.value)))

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

© www.soinside.com 2019 - 2024. All rights reserved.