这个有角度的应用程序发出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无法作为记录返回(请求主体未定义)
答案 0 :(得分:1)
在您的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);
}
答案 1 :(得分:1)
确保已将其添加到组件文件中
record = {
accountid: null
};
否则,它将显示未定义的错误
答案 2 :(得分:0)
尝试此代码。它将为您提供帮助。 HTML
<form [formGroup]="loginForm">
<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"
formControlName="accountid" required>
</div>
<button type="button" class="btn"
(click)="saveRecord(recordForm)"
[disabled]="recordForm.invalid">Create</button>
</form>
TS
this.recordForm = new FormGroup({
accountid: new FormControl('', [Validators.required]),
});
saveRecord(data) {
console.log(data.value);// nothing is printed
this.spinner.show();
console.log(data.value);
this.http.post('/api/accounts', data.value)
.subscribe(res => {
//status success or failure
})