【问题标题】:Angular - pass additional form data to the serverAngular - 将额外的表单数据传递给服务器
【发布时间】:2023-03-03 07:14:25
【问题描述】:

我有一个带有prod_nameprod_descprod_price 的基本 Angular 表单,我当然想在提交表单时发送到服务器。

但是我想发送额外的数据和平,我不想为此设置隐藏的输入字段。

所以形式的剥离版本看起来像这样:

<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() 函数中执行此操作,但我被卡住了。

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

【问题讨论】:

    标签: angular angular-forms angular-controller


    【解决方案1】:

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

      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`
        }
      }
    

    【讨论】:

    • 解决方案比我想象的要简单得多。我在搜索 Angular 对象和一些函数时迷失了方向。也许也可以使用数组表示法向对象添加数据而不复制它?还是抄袭更好?感谢您的回答以及设计模式的建议!
    • 表单对象本身(productForm)有很多额外的东西。您可以将其输出到控制台查看。最好将该对象的值复制到另一个对象并对其进行编辑。
    • 是的,实际上 onFormSubmit() 函数只传递了值,它在模板“(ngSubmit)="onFormSubmit(productForm.value)”中看起来像这样,这也将较小的对象传递给函数,因为 JavaScript 按值将参数传递给函数。我知道这并没有太大的速度改进,而是其中一件小事。
    • 啊,是的,我明白了。让我感到震惊的是:form: NgForm 作为数据类型。
    • 我现在已经删除了,它是其他人留下的代码,它也让我陷入了在NgForm 中搜索某些函数以添加新数据的错误轨道,但没有意识到它实际上是普通的 JavaScript 对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多