Angular 2 Serializing JSON Forms

I had a small problem with creating an Angular 2 form and converting the submitted data to JSON format for use in my API. I am looking for something that is very similar to this example: $.fn.serializeObject = function() http://jsfiddle.net/sxGtM/3/
The only problem with this example is that the code is written in JQuery, while I am trying to use strictly Angular 2. Any help would be greatly appreciated, I'm still very new to angular.

+4
source share
3 answers

If you use FormGroup, you can use the function getRawValue()to return an object, which can then be serialized with 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)
            );
    }
}
+9
source

You are looking for JSON.stringify(object)one that will provide you with a JSON representation of your javascript object.

You can then do a POST using the built-in HTTP service to your server.

+1
source

You can use JSON.stringify (form.value) . Please refer to the attached images.

enter image description here

Console Log: Console Log:

0
source

Source: https://habr.com/ru/post/1655805/


All Articles