我在表单对象parentForm中有一个名为'question1'的表单控件,我已按以下方式订阅了它.

这是一个带有YesNo两个选项的单选按钮,当我 Select No时,我得到Yes,当我 Select Yes时,我得到No.

this.parentForm.controls['question1'].valueChanges.subscribe(
  (selectedValue) => {
    // If option `No is selected`
    console.log(selectedValue);  // displays No. OK
    console.log(this.parentForm.value['question1']);  // displays Yes. Problem is here
  }
);

变量selectedValue的值是正确的,但是如果我取console.log(this.parentForm.value['question1'],它会给出之前的值.

在从this.parentForm.value['question1']中检索值之前,我试着输入setTimeout(),结果很好.

setTimeout(() => {
  console.log(this.parentForm.value['question1']); // gives the correct value.
}, 500);

但我的问题是,为什么parentForm在其控件的值更改时不更新,而且我也只是在值更改后才检索其值.

注:我不想遵守parentForm.valueChanges年,这不是我的要求.

推荐答案

valueChanges是可观察的,因此您可以通过管道pairwise获取订阅中的上一个和下一个值.

// No initial value. Will emit only after second character entered
this.form.get('fieldName')
  .valueChanges
  .pipe(pairwise())
  .subscribe(([prev, next]: [any, any]) => ... );
// Fill buffer with initial value, and it will emit immediately on value change
this.form.get('fieldName')
  .valueChanges
  .pipe(startWith(null), pairwise())
  .subscribe(([prev, next]: [any, any]) => ... );

在StackBlitz中工作的示例:

Update

如果你注意到startWith似乎是deprecated,情况并非如此.操作员只有一个活动签名,您可以在本answer页中阅读.

很可能,您使用的是startWith(null)或startWith(未定义),尽管有通知,但它们并没有被弃用,但IDE检测到错误的函数签名,该签名已被弃用,并显示警告.

一个简单的解决方法是提供预期的返回类型:

// Prevent deprecation notice when using `startWith` since it has not been deprecated
this.form.get('fieldName')
  .valueChanges
  .pipe(startWith(null as string), pairwise())
  .subscribe(([prev, next]: [any, any]) => ... );

它与startWith在StackBlitz中工作的示例:

Angular相关问答推荐

将kendo—colorpicker的kendo弹出窗口附加到组件''

如何在自定义验证器中获取所有表单控件(字段组动态创建)

为什么这个拦截器只在发送事件上触发,而不是在实际响应上触发?

Angular:将服务注入非独立组件导致应用程序中断

在RxJS和ANGING中处理多个API调用

ANGLE DI useFactory将参数传递给工厂函数

确保我的角库S服务构建提供独立的友好提供功能

如何从URL中角下载图片?

ngRouterOutlet和组件生命周期使用自定义模板渲染的问题

Angular JWT Token 被添加到lazyUpdate 而不是 HttpHeaders 中的标头

根据变量值更改按钮样式

我应该在 Jasmine 3 中使用什么来代替 fit 和 fdescribe?

全局异常处理

RxJS - .withLatestFrom 的多个来源

Angular ngFor 索引从 1 开始 循环

Angular2 CLI 错误@angular/compiler-cli包未正确安装

visibility:hidden

Angular 2 单元测试 - 出现错误无法加载ng:///DynamicTestModule/module.ngfactory.js

Angular单元测试输入值

使用 EventEmitter 传递参数