How to send form data in a http post request of angular 2?

akila arasan picture akila arasan · Dec 8, 2016 · Viewed 83.1k times · Source

I am trying to send form data of the updated user details to the back end which node server in angular 2,However I couldn't send the form data and the server responds with status of 500,In angularjs I have done something like this, service file

  update: {
    method: 'POST',
    params: {
      dest1: 'update'
    },
    transformRequest: angular.identity,
    'headers': {
      'Content-Type': undefined
    }
  }

In controller as

var fd = new FormData();
var user = {
  _id: StorageFactory.getUserDetail()._id,
  loc: locDetails
};
fd.append('user', angular.toJson(user));
UserService.update(fd).
$promise.then(
  function(value) {
    console.info(value);
    updateUserDetailsInStorage();
  },
  function(err) {
    console.error(err);
  }
);

I couldn't to figure how to do this in angular 2 as angular.toJson,angular.identity and transformrequest features are not available in angular 2, so far I have done the following in angular 2,

 let fd = new FormData();
 let user = {
   _id: this.appManager.getUserDetail()._id,
   loc: locDetails
 };
 fd.append('user', JSON.stringify(user));
 this.userService.update(fd).subscribe((value) => {
   console.log(value);
   this.updateUserDetailsInStorage();
 }, (err) => {
   console.error(err);
 });

http service file

update(body) {
  console.log('update', body);
  const headers = new Headers({
    'Content-Type': undefined
  });

  const options = new RequestOptions({
    headers: headers
  });
  return this.http.post(`${app.DOMAIN}` + 'user/update', body, options)
    .map((res: Response) => {
      res.json();
    }).do(data => {
      console.log('response', data);
    })
}

I have read many posts and tried few things but so far it was unsuccessful, could anyone suggest me how to do this?

Answer

Sahil Daga picture Sahil Daga · May 29, 2017

You can add headers if your server controller requires it else you can simply post it like this

let body = new FormData();
body.append('email', 'emailId');
body.append('password', 'xyz');
this.http.post(url, body);