Angular 8 个应用在使用 router.navigate 时无法检索表单字段值

Angular 8 app unable to retrieve form field value when using router.navigate

我有一个 Angular 8 应用程序,它使用路由和模板驱动的表单。

我在component.html中有一个简单的表格:

<form (ngSubmit)="onSubmit(serviceForm)" #serviceForm="ngForm">
  <input type="text" name="endpoint" ngModel>
  <button class="btn btn-success" type="submit">Submit</button>
</form>

component.ts中的处理程序:

onSubmit(serviceForm:NgForm){
  console.log(serviceForm);
  this.router.navigate(['/view-service']);
 }
当我在 console.log() 之后调用导航语句时,

"Endpoint" 在 ngForm.value 中不可用。这是 console.log:

的输出

NgForm {submitted: true, _directives: Array(1), ngSubmit: EventEmitter, form: FormGroup}
表单指令:(...)
控制:(...)
路径:(...)
控制:(...)
值:对象
__proto__: 对象

有效:(...)
无效:(...)
待处理:(...)
禁用:(...)
已启用:(...)
错误:(...)
原始:(...)
脏:真
感动:真实
状态:(...)
未受影响:(...)
状态变化:(...)
值变化:(...)
提交:true

如果我不调用导航语句,它是可用的。

我不明白,我在导航之前打印到控制台。

我做错了什么?

谢谢!

这是因为您正在查看表单,但您想要的是表单中包含的特定值。将您的代码更改为以下内容:

onSubmit(serviceForm: NgForm){
  console.log(serviceForm.value.endpoint);
}

我创建了一个 demo app on stackblitz that illustrates this using your exact form. Also - be sure to read the docs on forms

编辑以解决您编辑的问题

您正在记录一个 reference 到您的表单对象,但是当您在开发工具中检查它时,您已经离开页面,并且表单值是因此不可用。 MDN Web Docs 中对此进行了解释。具体来说:

Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you open the console.

试试 MDN 的建议:

Logging objects

Don't use console.log(obj), use console.log(JSON.parse(JSON.stringify(obj))).