Angular 2表单序列化为JSON格式

Tri*_*n C 9 forms json angular

我在创建Angular 2表单时遇到了一些麻烦,并将提交的数据转换为JSON格式,以便将其提交给我的API.我正在寻找与此示例非常相似的东西:$.fn.serializeObject = function() http://jsfiddle.net/sxGtM/3/此示例
的唯一问题是代码是用JQuery编写的,而我正在尝试使用严格的角度2任何帮助都会非常感激,我仍然很有棱角.

Fed*_*lla 21

getRawValue()如果您正在使用a FormGroup,则可以使用该函数来返回可以使用其进行序列化的对象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)
            );
    }
}
Run Code Online (Sandbox Code Playgroud)


Mah*_*pal 5

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));
}
Run Code Online (Sandbox Code Playgroud)

Result in Chrome DevTools: 的console.log结果