Angular 反应形式:valueChanges 没有按预期工作

Angular reactive forms: valueChanges doesn't work as expected

我正在学习在 Angular 6 中使用 Reactive Forms,如果这个问题很愚蠢,请原谅我,但这是我的问题:

我想监视我的反应形式中某个值的变化,因为当发生变化时,我需要 运行 一些根据新值重新计算内容的逻辑。所以我试过这样做:

this.inputGroup = formBuilder.group({
  myControl: 'something'
});

this.inputGroup.get('myControl').valueChanges.subscribe(newVal => {
  console.log("new value", newVal); //Prints the correct new value
  console.log("actual value", this.inputGroup.value.myControl); //Prints the previous (old) value!

  this.someFuncThatExpectsTheValuesToBeUpToDate(); //This will find the OLD value inside this.inputGroup.value.myControl, instead of the new one!
});

但是,正如您从我在代码中添加的注释中看到的那样,这不起作用,因为 valueChanges 似乎在 之前被调用 该值实际上是模型改变了!这是有意的行为吗? valueChanges 的方法签名说:

A multicasting observable that emits an event every time the value of the control changes, in the UI or programmatically.

所以我假设它是在表单中的值被更改之后调用的,但显然不是......这是正确的吗?如果是这样,我如何检测控件中的值何时实际发生变化?

EDIT:关于为什么我希望我的函数直接从 Form 组访问数据,而不是将新值传递给函数本身。这很容易解释:该函数从多个表单组收集数据,并使用这些数据进行一些辅助计算。通过直接从表单组访问数据,该函数是通用的,可以从任何地方调用。如果我开始将输入参数放在那里,这将会中断。举个例子:

someFuncThatExpectsTheValuesToBeUpToDate(){
  let val1 = inputGroup.value.myControl;
  let val2 = someOtherFormGroup.value.myOtherControl;
  let val3 = yetAnotherFormGroup.value.someOtherControl;
  //do something with the vals
}

有了这个功能,我可以从任何地方调用它,它会起作用。但是如果我需要每次都传入值,我将需要 3 个具有不同签名的不同函数来做同样的事情,更加混乱和复杂。

valueChanges 事件在新值更新为 FormControl 值之后,并且在更改冒泡到其父级和祖先级之前被触发。因此,您必须访问 FormControl 本身的值,而不是 FormGroup 值对象的字段。

console.log this.inputGroup.get('myControl').value 在订阅中,它将具有新值。