Angular 2 Form Serialization Into JSON Format
You can use JSON.stringify(form.value)
:
submit() {
let resource = JSON.stringify(this.form.value);
console.log('Add Button clicked: ' + resource);
this.service.create(resource)
.subscribe(response => console.log(response));
}
Result in Chrome DevTools:
You can use the getRawValue()
function if you're using a FormGroup
, to return an object that can then be serialized using JSON.stringify()
.
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Http } from '@angular/http';
@Component({
selector: 'my-component',
templateUrl: 'my-component.component.html'
})
export class MyComponent implements OnInit {
form: FormGroup;
constructor(private fbuilder: FormBuilder,
private http: Http) { }
ngOnInit(){
this.form = this.fbuilder.group({
name: '',
description: ''
});
}
sendToAPI(){
let formObj = this.form.getRawValue(); // {name: '', description: ''}
let serializedForm = JSON.stringify(formObj);
this.http.post("www.domain.com/api", serializedForm)
.subscribe(
data => console.log("success!", data),
error => console.error("couldn't post because", error)
);
}
}
You are looking for JSON.stringify(object)
which will give you the JSON represantation of your javascript object.
You can then POST this using the built-in HTTP service to your server.