【问题标题】:How to Stringify Angular FormArray in order to send it to the server如何对 Angular FormArray 进行字符串化以将其发送到服务器
【发布时间】:2018-04-19 13:26:21
【问题描述】:

在 Angular 项目中,我有一个包含 FormControls 的 FormArray,我不知道如何对这个 FormArray 进行字符串化以便将其发送到服务器。这是代码、Submit 方法和我制作 Observable 的服务。请帮忙。

onSubmit(){
    let formControls = new FormArray([]);
    formControls = <FormArray>this.reviewForm.get('controlArray');
    this.formService.createForm(formControls)
      .subscribe(
        data => console.log(data),
        error => console.error(error)
    );
    this.reviewForm.reset();
    // console.log(formControls);        
  }

@Injectable()
export class FormService {
    constructor(private http: Http) {}

    createForm(formControls: FormArray) {
        const body = JSON.stringify(formControls); //this gives error
        const headers = new Headers({'Content-Type': 'application/json'});
        return this.http.post('http://localhost:3000/api/form', body, {headers: headers})
            .map((response: Response) => response.json())
            .catch((error: Response) => Observable.throw(error.json()));
    }

}

【问题讨论】:

  • 你试过JSON.stringify(this.reviewForm.value.controlArray)吗?
  • 我应该在提交方法中还是在服务中对其进行字符串化?
  • 我觉得没关系。
  • 它对我有用。非常感谢

标签: angular angular-reactive-forms formarray


【解决方案1】:

您可以使用getRawValue() 方法。

formControls.getRawValue();

【讨论】:

    【解决方案2】:

    只需获取值并将其字符串化:

    JSON.stringify(this.reviewForm.value.controlArray)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 2015-10-20
      相关资源
      最近更新 更多