我正在尝试将表单数据用于数据库,我正在尝试将数据添加到数据库中,我想我错过了一些东西。 我是新手,想要学习,我不知道如何使用post方法,我应该把什么放入json stringify。请有人帮忙。 这是我的模板
<form (ngSubmit)="onSubmit()" [ngFormModel]="form" #f="ngForm">
<div class="form-row">
<div class="formHeading">Facebook</div>
<input type="text" id="fb" ngControl="fb">
<div class="errorMessage" *ngIf="f.form.controls.fb.touched && !f.form.controls.fb.valid">Facebook address is required</div>
</div>
<div class="form-row">
<div class="formHeading">Google</div>
<input type="text" id="gl" ngControl="gl">
<div class="errorMessage" *ngIf="f.form.controls.gl.touched && !f.form.controls.gl.valid">Google address is required</div>
</div>
<div class="form-row">
<div class="formHeading">Twitter</div>
<input type="text" id="twt" >
</div>
<div class="form-row">
<div class="formHeading">LinkedIn</div>
<input type="text" id="li" >
</div>
<div class="form-row">
<button type="submit" [disabled]="!f.form.valid">Save</button>
</div>
我的组件
import {Component} from '@angular/core';
import {FormBuilder, Validators, ControlGroup, FORM_DIRECTIVES} from '@angular/common';
import {Http, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Subject } from 'rxjs/Subject';
@Component({
selector: 'social-form',
directives:[FORM_DIRECTIVES],
templateUrl: './components/social/social.html',
providers: [FormBuilder]
})
export class Social {
http;
form;
constructor(fb: FormBuilder) {
this.form = fb.group({
"fb": ['', Validators.required],
"gl": ['',Validators.required],
});
}
onSubmit() {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://www.syntaxsuccess.com/poc-post/', JSON.stringify({?????????????}),{headers:headers})
.map((res: Response) => res.json())
}
}
I am trying to add my data to database,i think i missed something.
I am new to angular trying to learn and i dont know how to use post method and what should i put into json stringify.Please can someone help.
答案 0 :(得分:0)
您可以将ngForm值传递给onSubmit()方法:
<form #f="ngForm" (ngSubmit)="onSubmit(f.value)">
然后:
onSubmit(form:any) {
let body = JSON.stringify({ form });
let headers = new Headers({ 'Content-type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url, body, options)
.map((res: Response) => res.json())
.subscribe();
}
请勿忘记subscribe();
,因为http.post
尚未发送请求!这种观察结果是冷的,这意味着请求不会出现,直到某些内容订阅了可观察的内容