Angular 2将表单序列化为JSON格式 [英] Angular 2 Form Serialization Into JSON Format
问题描述
创建我的Angular 2表单并将提交的数据转换为JSON格式以用于将其提交给我的API时遇到了一些麻烦。我正在寻找一些与此示例非常相似的东西:
$。fn.serializeObject = function()
http://jsfiddle.net/sxGtM/3/
这个例子的唯一问题是代码是用JQuery编写的,而我试图使用严格的角度2.
任何帮助将不胜感激,我仍然是非常新的角。
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 something that works very similarly 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, whereas I'm trying to use strictly angular 2.
Any help would be greatly appreciated, I am still very new to angular.
推荐答案
如果您使用 FormGroup
,您可以使用 getRawValue()
函数返回然后可以使用 JSON.stringify()
。
If you're using a FormGroup
, you can use the getRawValue()
function 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)
);
}
}
这篇关于Angular 2将表单序列化为JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!