【问题标题】:Angular 2 Form Serialization Into JSON FormatAngular 2 形式序列化为 JSON 格式
【发布时间】:2016-09-26 08:42:35
【问题描述】:

我在创建 Angular 2 表单并将提交的数据转换为 JSON 格式以便将其提交到我的 API 时遇到了一些麻烦。我正在寻找与此示例非常相似的东西: $.fn.serializeObject = function() http://jsfiddle.net/sxGtM/3/
这个例子的唯一问题是代码是用 JQuery 编写的,而我试图严格使用 angular 2。 任何帮助将不胜感激,我对 Angular 还是很陌生。

【问题讨论】:

  • 如果您使用的是 Angular,那么为什么您的输入中没有 ngmodel?
  • 因为这是我找到的示例,而不是我的代码。我想使用 angular 2 实现与此示例类似的东西

标签: json forms angular


【解决方案1】:

如果您使用FormGroup,则可以使用getRawValue() 函数返回一个对象,然后可以使用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)
            );
    }
}

【讨论】:

    【解决方案2】:

    你可以使用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));
    }
    

    Chrome DevTools 中的结果:

    【讨论】:

      【解决方案3】:

      您正在寻找JSON.stringify(object),它将为您提供 javascript 对象的 JSON 表示。

      然后您可以使用内置 HTTP 服务将其发布到您的服务器。

      【讨论】:

      • FormGroups 可以并且通常确实包含循环引用,因此除非您自定义 stringify 函数,否则此解决方案将不起作用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多