I have a form ‘myForm’ which is a form group and has two form controls. I wish to collect the input the user made on these two form controls and post it to a webserver.
My question here is how to ‘collect’ the values of the form controls? I am pretty sure this is an easy question but I could not find the documentation to do so.
contact.ts
import { Component } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { NavController } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup, AbstractControl } from '@angular/forms';
import 'rxjs/add/operator/map';
import { ContactService } from './contact.service';
@Component({
selector: 'page-contact',
templateUrl: 'contact.html',
providers: [ContactService]
})
export class ContactPage {
private myForm: FormGroup;
purFreq: AbstractControl;
purFreqFac: AbstractControl;
constructor(private contactService: ContactService, public navCtrl: NavController, private formBuilder: FormBuilder, public http: Http) {
this.myForm = this.formBuilder.group({
purFreq: [''/*, Validators.required*/],
purFreqFac: [''],
});
this.purFreq = this.myForm.controls['purFreq'];
this.purFreqFac = this.myForm.controls['purFreqFac'];
}
onSubmit(value){
this.contactService.sendToPhp({value})
.subscribe(data => {
console.log(data);
},
error => {
console.log("error posting form to php");
});
}
}
contact.service.ts
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Headers, URLSearchParams, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class ContactService {
constructor (private http: Http) {}
sendToPhp(o:any): Observable<any> {
const body = new URLSearchParams(o);
body.set('purFreq', o.purFreq);
body.set('purFreqFac', o.purFreqFac);
console.log(body.toString);
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post('url', body.toString(), {
headers : headers
}).map(res => res.json());
;
}
}