11

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.

5
  • You're asking a lot of questions but not including error details in regards to your actual problem. What type of error are you getting from your API? The method you've implemented of using the Angular HTTP package is what most people use. To be clear though, the second argument of the .post() method attaches the value to the body of the request. That means it has to be parsed from the body, and will not come from the query string. This configuration can be determined at your API level. Jun 14, 2017 at 21:00
  • The method i have commented out did not send the post request. At least it seemed so because i didn't see any requests going out from chromes developer tools network tab. Jun 14, 2017 at 21:03
  • And you're not seeing any errors in the console? If so, it could possibly be a CORS issue. If not, it makes it a bit harder to chase down. Did you import the Http package from '@angular/http' at the top of your file, and then use the DI engine to inject it into that component inside of the constructor via private _http: Http? Jun 14, 2017 at 21:06
  • Wouldnt i see a outgoing request if it was a CORS problem? I did all the next steps you mentioned. Ill try to create a clean project so reproduce the problem and link it here. Jun 15, 2017 at 5:49
  • 1
    Added an anwser. Seems i was missing .subscribe. Also puting "user" straight into post doesent add a body to the request. Had to recreate it manually. Jun 15, 2017 at 6:47

4 Answers 4

22

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); 
}
3
13

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.

3
  • Same problem here ! A little bit angry about not founding solution for such a simple problem. http.post vs http.request ; .toPromise().then... vs .subscribe(). returning an Observable or not ? I feel LOST ! Aug 24, 2017 at 14:18
  • Oups, if you're doing Angular4 versus a Spring Data Rest projet, don't forget to consider the bug jira.spring.io/browse/DATAREST-573. Angular doest OPTIONS before POST, so OPTIONS must be allowed from your REST server. Aug 25, 2017 at 6:30
  • This worked for me. My settings: Angular 6 + Restful API which requires a form data object. Thanks for posting. Dec 19, 2018 at 20:18
6

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.

2
  • What is doing the subscribe(status=> console.log(JSON.stringify(status))? Just reciving a 200ok?
    – ValRob
    Apr 5, 2018 at 19:51
  • 1
    @ValRob Post is normally when you create a record. So you'd problably want to get the object back. Don't mistaken status with HttpStatus there. status above is just a placeholder for what you get back. I should have renamed it to data.
    – Mukus
    Apr 6, 2018 at 0:36
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.