How is it possible to post form data to an external rest api?
At the moment i have an html form:
Let me contribute to the accepted answer since I don't have enough reputation to comment. Rather than pick all the form inputS one by one into a model, you could do the following
var model = this.forContollname.value
Then you could call the following
var values = JSON.stringify(model)
The values can then be passed into your post method. I hope this simplifies the process for someone with a large form.
For Making as generic Post
& Get
Method in angular 2/4 using form data
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
constructor(private _http: Http) { }
get(url: string): Observable < any > {
return this._http.get(url)
.map((response: Response) => <any>response.json());
}
post(url: string, model: any): Observable <any> {
let formData: FormData = new FormData();
formData.append('id', model.id);
formData.append('applicationName', model.applicationName);
return this._http.post(url, formData)
.map((response: Response) => {
return response;
}).catch(this.handleError);
}
Ok, so it turns out i have to add .subscribe() to post for it to do something. Also if i put "user" straight into post request for some reason it sends an request with method "OPTIONS" without a body. So i have to create a queryParams string myself. If anyone can explain this or show a better way to do this i would appriciate it. Otherwise this currently works:
onSubmit = function (user) {
console.log(user);
var body = "firstname=" + user.firstname + "&lastname=" + user.lastname + "&name=" + user.name;
this.http.post("http://www.testtttt.com", body).subscribe((data) => {});
}
Edit: another and probably even a better solution is to use JSON.stringify(user) instead of body. But subscribe() is still needed tho.
How about using Typescript to make your life easier?
The html has ngModel
two way binding.I've changed to rename the form personForm. You can add validation, but I have skipped it here.
<form #personForm="ngForm"(ngSubmit)="onSubmit(personForm.value)">
<input name="firstName" [(ngModel)]="firstName">
<input name="lastName" [(ngModel)]="lastName">
<button type="submit">Save</button>
</form>
On the component, you can use an interface Person which you can define in a models folder. The contents looks like this.
export interface Person {
id:number;
firstName: string;
lastName: string;
}
And then in the submit method you can map it automatically like below.
onSubmit(person: Person){
http.post('your_url', person).subscribe(status=> console.log(JSON.stringify(status)));
}
See how easy it is type safety? Also you can check if id is populated and either make a 'PUT' or 'DELETE' request depending on whether you want to update the person or delete.