Angular 6 FormArray作为数组发送

问题描述 投票:0回答:3

我的网站上有Reactive Forms,它使用FormBuilder。

我有两个字段有FormControls和用户创建的字段数组FormArray

当我向服务器发送数据时,发现FormArray发送的是带有逗号的列出项目的字符串而不是数组。

如何使用数组将数据发送到服务器?

那是我的班级方法

formGroup = this.fb.group({
    link: [null, [
      Validators.required,
      Validators.pattern(/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/)
    ]],
    image: [null, Validators.required],
    features: this.fb.array([this.fb.control('', Validators.required)])
  });

beforeSubmit(): FormData {
    const formData = new FormData();

    formData.append('link', this.link.value);
    formData.append('image', this.image.value);
    formData.append('features', this.features.value);

    return formData;
  }

  submit() {
    console.log('submit');

    const formData = this.beforeSubmit() as FormData;

    this.ss.postSite(formData).subscribe(
      response => {
        console.log(response);
      }
    );

  }

和服务

postSite(input: FormData) {
    console.log('posting');

    return this.http.post<Site>(this.API_URL, input, this.HEADERS).pipe(
      catchError(this.handleError)
    );
  }
javascript angular forms api typescript
3个回答
0
投票

formData.append('features', this.features.value);改为

this.features.getRawValue().forEach(e => {
  formData.append('features[]', e);
});

因此,我们迭代rawValues这是一个数组。


-1
投票

它不是FormArray问题。 FormData map数组到字符串。尝试使用此解决方案。

submit() {
   console.log('submit');
   const formData = this.formGroup.value;

   this.ss.postSite(formData).subscribe(
     response => {
       console.log(response);
     }
   );

 }

需要使用<input type="file" />发送文件时使用FormData


-1
投票

FormArray将每个子FormControl的值聚合到一个数组中

您必须按照iuser输入将FormControls推送到FormArray。如果您已经这样做,请分享该代码部分

© www.soinside.com 2019 - 2024. All rights reserved.