Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  24] [ 7]  / answers: 1 / hits: 117408  / 7 Years ago, wed, june 14, 2017, 12:00:00

How is it possible to post form data to an external rest api?



At the moment i have an html form:



<form [formGroup] = form (ngSubmit) = onSubmit(form.value)>
<input name=name formControlName=name>
<input name=first_name formControlName=first_name>
<input name=last_name formControlName=last_name>
<button type=submit>Save</button>
</form>


and then i have the function that is handling the submit in my component.ts file:



  onSubmit = function (user) {
console.log(user);
//this.http.post('http://xxx/externalapi/add', user);
}


But how is it possible to post the form data to my external api? And what is the standard of sending form data with angular? Is it just a simple post request with form data as queryParams or is it standard to convert it into JSON. I can modify the api to handle whatever data is sent so thats not a problem.


More From » angular

 Answers
7

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.


[#57451] Tuesday, June 13, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austynp

Total Points: 505
Total Questions: 118
Total Answers: 106

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
austynp questions
;