提交表单时为什么我的FormData为空?

时间:2019-12-12 19:54:10

标签: javascript angular typescript forms ionic-framework

我的formData使用反应形式的输入:categoryForm。我必须这样做才能上传数据。但是,当我提交formData并进行console.log记录时,我得到的只是FormData {},所以是一个空表格。但是我不知道为什么,因为我用this.categoryForm.get('name').value来获取每个数据的价值 我的反应式表单实际上正在接收数据,并且该表单具有所有数据,所以问题是formData无法获取数据。

html:

<form [formGroup]="categoryForm">
                    <ion-item mode="ios" lines="none" class="checkbox-tag rounded-tag">
                        <ion-icon name="eye"></ion-icon>
                      <ion-checkbox formControlName="lock"></ion-checkbox>              

<div> 
    <ion-item>
      <ion-input [disabled]="tagList?.length > 0" mode="md" formControlName="category" clearInput="true" placeholder="Tag" name="tagValue"></ion-input>
      <ion-button (click)="addTag()" [disabled]="!categoryForm.valid || tagList?.length > 0"  item-right icon-only>
      <ion-icon name="checkmark"></ion-icon>
    </ion-button>
    </ion-item>
</div>

</form>

</ion-content>

<ion-footer">

        <ion-button 
        [disabled]="!tagList?.length > 0" 
        (click)="apiSubmit()"
        expand="block" 
        color="secondary" 
        fill="solid"
        >POST</ion-button>
  </ion-footer>

ts:

     ngOnInit() {

  this.storage.get('image_data').then((imageFile) => {
      console.log(imageFile)
      this.categoryForm.patchValue({
        'image': this.storage.get('image_data')
      });

      this.storage.get('when').then((whenData) => {
        this.categoryForm.patchValue({
          'when': this.storage.get('when')
        });
      });
    });

        this.categoryForm = new FormGroup({

          'lock': new FormControl(true),


          'category': new FormControl('', Validators.compose([
            Validators.maxLength(25),
            Validators.minLength(1),
            Validators.required
          ])),

          'image': new FormControl(null),
          'when': new FormControl(null),
        });

    }

    apiSubmit() {
      const formData = new FormData();
      formData.append('lock', this.categoryForm.get('lock').value);
      formData.append('category', this.categoryForm.get('category').value);
      formData.append('image', this.categoryForm.get('image').value);
      formData.append('when', this.categoryForm.get('when').value);
      console.log(formData);

      this.http.post<any>(`{this.url}`, formData, httpOptions).subscribe(
        (res) => console.log(res),
        (err) => console.log(err)
      );
    }

1 个答案:

答案 0 :(得分:0)

为什么不使用categoryForm本身来获取值,像这样:

const value = this.categoryForm.value