Angular 2 Form Serialization Into JSON Format

前端 未结 3 1617
无人共我
无人共我 2021-02-05 15:14

I am having a little bit of trouble creating my Angular 2 form and converting the submitted data into JSON format for the use of submitting it to my API. I am looking for someth

3条回答
  •  离开以前
    2021-02-05 15:30

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

提交回复
热议问题