Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 902
akila arasan Avatar asked Dec 08 '16 04:12

akila arasan


Video Answer


2 Answers

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);
like image 138
Sahil Daga Avatar answered Oct 19 '22 03:10

Sahil Daga


Here is the method I've used in angular 4 for uploading files.... for Ui

   <input type="file"id="file"(change)="handleFileInput($event)">

and .ts file I've added this ....

  handleFileInput(event) {
    let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
    let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
    let files: FileList = target.files;
    this.fileToUpload  = files[0];
    console.log(this.fileToUpload);
  }



 uploadFileToActivity() {
    console.log('Uploading file in process...!' + this.fileToUpload );
    this.fontService.upload(this.fileToUpload).subscribe(
      success => {
        console.log(JSON.stringify(this.fileToUpload));
        console.log('Uploading file succefully...!');
        console.log('Uploading file succefully...!' + JSON.stringify(success));
      },
      err => console.log(err),
    );
  }

and In services

upload(fileToUpload: File) {
    const headers = new Headers({'enctype': 'multipart/form-data'});
    // headers.append('Accept', 'application/json');
    const options = new RequestOptions({headers: headers});
    const formData: FormData = new FormData();
    formData.append('file', fileToUpload, fileToUpload.name);
    console.log('before hist the service' + formData);
    return this.http
      .post(`${this.appSettings.baseUrl}/Containers/avatar/upload/`, formData , options).map(
        res => {
          const data = res.json();
          return data;
        }
      ).catch(this.handleError);
  }

This method used for single file uploading to the server directory.

like image 30
muhammad zaman Avatar answered Oct 19 '22 04:10

muhammad zaman