2

In Angular project I have a FormArray containing FormControls, I don't know how to stringify this FormArray in order to send it to server. Here is the code, the Submit method and the service where I make Observable. Please help.

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()));
    }

}
4
  • 1
    Have you tried JSON.stringify(this.reviewForm.value.controlArray)? Commented Nov 7, 2017 at 8:16
  • should I stringify it in submit method or in the service? Commented Nov 7, 2017 at 8:18
  • I think it doesn't really matter. Commented Nov 7, 2017 at 8:19
  • It worked for me. Thanks alot Commented Nov 7, 2017 at 8:27

2 Answers 2

1

Just get the value and stringify it:

JSON.stringify(this.reviewForm.value.controlArray)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the getRawValue() method.

formControls.getRawValue();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.