angular - 无法在发布请求Angular 6 Form组中传递值
问题描述
这个 Angular 应用程序发出 http.post 请求,我通过 form-group 传递这个 API 的正文。这是代码片段
<mat-tab-group>
<mat-tab label="New Account">
<br><br>
<button class="btn" type="button" (click)="saveRecord()" [disabled]="!recordForm.form.valid">Create</button>
<form #recordForm="ngForm">
<div class="form-group">
<label class="col-sm-6 col-form-label" for="name">Customer Number</label>
<input type="text" class="form-control col-sm-6" [(ngModel)]="record.accountid" name="accountid" required>
</div>
我将 accountid 传递给函数(saveRecord),点击按钮,如上图所示
我看到记录变量没有任何值,尽管它是从表单组传递的
saveRecord() {
console.log(this.record);// nothing is printed
this.spinner.show();
console.log(this.record);
this.http.post('/api/accounts', this.record)
.subscribe(res => {
//status success or failure
})
API 无法作为记录返回(请求正文未定义)
解决方案
在您的 HTML 中
<button class="btn" type="button" (click)="saveRecord(recordForm)" [disabled]="!recordForm.form.valid">Create</button>
<form #recordForm="ngForm">
<div class="form-group">
<label class="col-sm-6 col-form-label" for="name">Customer Number</label>
<input type="text" class="form-control col-sm-6" [(ngModel)]="record.id" name="accountid" required>
</div>
</form>
在你的 ts 文件中
record = {id:null};
saveRecord(form:NgForm) {
console.log(form.value);
}
推荐阅读
- csv - 当它不是文件的第一行时如何自动设置标题?
- ssms - SQL Server Management Studio 17.9 字体大小不起作用
- javascript - $(document).ready 故障,$(document).resize 有效 - 相同的处理程序
- java - OpenJDK 11.0.2 的 Spring Boot 2.0 请求映射问题
- python - 选择多个单词的首字母
- azure - 如何向 Azure 虚拟机规模集添加第二个网络接口?
- json - 在 vuejs 中反序列化来自 laravel 的数据
- android - 无法在长按图像上保存从 WebView 下载 Facebook 图像
- http - 关于我的浏览器发送的 HTTP 请求的问题
- css - 选中 td 中的复选框时更改 tr 背景颜色