Waleed Shahzaib
Waleed Shahzaib

Reputation: 1706

How to Stringify Angular FormArray in order to send it to the server

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

}

Upvotes: 2

Views: 1678

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657396

Just get the value and stringify it:

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

Upvotes: 1

JsFan
JsFan

Reputation: 443

You can use the getRawValue() method.

formControls.getRawValue();

Upvotes: 1

Related Questions