Angular - 向服务器传递额外的表单数据

Angular - pass additional form data to the server

我有一个基本的 Angular 表单,其中包含 prod_nameprod_descprod_price,这些当然是我想在提交表单时发送到服务器的。

但是我想发送额外的数据,我不想为此创建隐藏的输入字段。

所以表格的剥离版本看起来像这样:

<form [formGroup]="productForm" (ngSubmit)="onFormSubmit(productForm.value)">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Product Name" formControlName="prod_name"
           [errorStateMatcher]="matcher">

  </mat-form-field>

 <!-- Additional two form fields omitted for clarity -->

  <div class="button-row">
    <button type="submit" [disabled]="!productForm.valid" mat-flat-button color="primary"><mat-icon>save</mat-icon></button>
  </div>
</form>

基本上它调用 onFormSubmit() 并传递给它 productForm.value.

这是控制器的样子,为了清楚起见,只删除了必要的数据:

@Component({
//...
})
export class ProductAddComponent implements OnInit {

  productForm: FormGroup;
  updated_at: Date = null;

  constructor(private router: Router, private api: ApiService, private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.productForm = this.formBuilder.group({
      'prod_name' : [null, Validators.required],
      'prod_desc' : [null, Validators.required],
      'prod_price' : [null, Validators.required]
    });
  }

  onFormSubmit(form: NgForm) {
    // Here I want to add current date as well to the form data before sending it
    this.api.addProduct(form)
      .subscribe(res => {
          let id = res.id;
          this.router.navigate(['/product-details', id]);
      }, err => {
          console.log(err);
      });
  }

}

onFormSubmit() 函数中,我也想将当前日期传递给服务器。
表单模板中的隐藏字段不是选项。
我想在调用服务之前在 onFormSubmit() 函数中执行此操作,但我被卡住了。

对于如何基本设置附加数据以及表单数据(例如日期)并将其发送到服务器,我将不胜感激。

您可以复制表单数据,然后添加任何您想要的内容。

  onFormSubmit(form: NgForm) {
    const dataForSubmit = {...form.value}; // copies the form data into a new variable
    dataForSubmit.otherProperty = 'what ever you want'; // add whatever data is needed
    this.api.addProduct(dataForSubmit)
      .subscribe(res => {
          let id = res.id;
          this.router.navigate(['/product-details', id]);
      }, err => {
          console.log(err);
      });
  }

在我的应用程序中,我经常为所有数据定义一个接口。我将该数据输入该界面,只将我想要的字段复制到表单中。然后在保存时,将更改从表单复制到原始对象。

界面

export interface Product {
  id: number;
  productName: string;
  productCode: string;
}

当然系统id不会出现在UI.

组件代码

// Update the data on the form
// after a get
this.productForm.patchValue({
  productName: this.product.productName,
  productCode: this.product.productCode
});

// The save
  saveProduct(): void {
    if (this.productForm.valid) {
       // Copies any changed form values over the original product values
       const p = { ...this.product, ...this.productForm.value };

       // Call the http service put to save the data `p`
    }
  }