2016-09-26 78 views
3

我在創建Angular 2表單並將提交的數據轉換爲JSON格式以便將其提交給我的API時遇到了一些麻煩。我正在尋找一些與此示例非常類似的東西: $.fn.serializeObject = function() http://jsfiddle.net/sxGtM/3/
此示例唯一的問題是代碼是用JQuery編寫的,而我試圖嚴格使用角度2. 任何幫助都將不勝感激,我對角度還是很陌生的。將Angular 2 Form序列化爲JSON格式

+0

如果您使用的角度,那麼爲什麼有一個在您輸入沒有ngmodel? –

+0

因爲這是我找到的例子,而不是我的代碼。我想用angular 2來實現類似於這個例子的東西 –

回答

1

您正在尋找JSON.stringify(object)它會給你的JavaScript對象的JSON represantation。

然後,您可以使用內置HTTP服務將此內容發佈到您的服務器。

8

如果您使用的是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) 
      ); 
    } 
} 
0

您可以使用JSON.stringify(form.value)。請參閱附件中的圖片。

enter image description here

控制檯登錄: Console Log: