首页 > 解决方案 > 无法在发布请求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>&nbsp;&nbsp;&nbsp;

 <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 无法作为记录返回(请求正文未定义)

标签: angulartypescriptrestapi

解决方案


在您的 HTML 中

<button class="btn" type="button" (click)="saveRecord(recordForm)" [disabled]="!recordForm.form.valid">Create</button>&nbsp;&nbsp;&nbsp;

 <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);
  }

推荐阅读