首页 文章

存储数据的角度反应形式

提问于
浏览
1

之前我使用过模板驱动的表单,我对于反应式表单如何将数据存储到我的数据库感到有些困惑。最初我会使用**[1] =“user.date”**。如何在提交时存储数据?我建了一个如下:

this.formGroup = this._formBuilder.group({
  formArray: this._formBuilder.array([
    this._formBuilder.group({
      dateFormCtrl: ['', Validators.required]
    }),
    this._formBuilder.group({
      emailFormCtrl: ['', Validators.email]
    }),
  ])
});

这是我想要存储到 db 的输入示例:

<input formControlName="dateFormCtrl" matInput [matDatepicker]="picker" [max]="maxDate" [min]="minDate" placeholder="When is your event?"(click)="picker.open()" readonly>

ATM 我有这个功能,我为模板驱动的表单存储数据:

create() {
    this.http.post('http://localhost:3000/user', this.user).subscribe(res => { ............

2 回答

  • 0

    如果要将表单数据动态保存到服务器,则可以按照以下代码进行操作。这是最好的选择。

    在您的 component.ts 文件中:

    form: FormGroup;
      payLoad = '';
    
        onSubmit() {
            this.payLoad = JSON.stringify(this.form.value);
    
            this.serverService.storeServers(this.payLoad)
            .subscribe(
              (response) => console.log(response),
              (error) => console.log(error)
            );
    
          }
    

    在您的 service.ts 文件中:

    constructor(private http: HttpClient) { }
      storeServers(payLoad: any) {
        const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type':  'application/json'
          })
        };
        return  this.http.post(' ***Complete URL*** ', payLoad, httpOptions);
      }
    
  • 1

    你的表格应该是这样

    this.form = this._formBuilder.group({
           dateFormCtrl: ['', Validators.required],
           emailFormCtrl: ['', Validators.email]
        });
    

    你的提交方法应该是这样

    onSubmit(): void{
           const formObj ={
            date: this.form.value.dateFormCtrl,
            email: this.form.value.emailFormCtrl,
           }
          this.http.post('http://localhost:3000/user', formObj).subscribe(res =>
        }
    

相关问题