Monday 19 March 2018

Send FormData using httpClient in Angular

Angular 2(+)Angular 4/5FormDatahttpClient

In this article we are going to discuss about sending data as FormData using httpClient in Angular. In my previous article I have explained about making an http call using httpClient. This is supported by Angular version 4.3 onwards. Any version below should use default http.

Let us check with an example for sending FormData. I have used FormData in my previous article for uploading a file and send data along with that. Check below code for sending FormData.

Component


<button class="btn" (click)="sendDataAsFormBody()">sendData</button>


import { Component } from '@angular/core';
import { CommonService } from '../../services/common.service';

@Component({
  selector: 'app-general',
  templateUrl: './general.component.html',
  styleUrls: ['./general.component.scss']
})
export class GeneralComponent {
  item: any;

  constructor(private commonService: CommonService) { }

  sendDataAsFormBody() {
    let fData: FormData = new FormData;
    fData.append("key1", 'Angular');
    fData.append("key2", 'JavaScript');
    fData.append("key3", 'React');

    this.commonService.sendData(fData).subscribe(
      data => {
        console.log(data);
      },
      error => {
        console.log(error);
      }
    )
  }
}

Here we are appending key value pair in FormData. You can loop it and add the data as well. Now check service file.

Service file


import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';


@Injectable()
export class CommonService {

  _url: string;

  constructor(private http: HttpClient) { }

  sendData(item) {
    this._url = '/api/add/data';

    return this.http.post(this._url, item, {
      headers: { 'Content-type': 'application/x-www-form-urlencoded; charset=utf-8' }
    })
      .map((response: Response) => {
        return response;
      });

  }
}

Here I am passing headers as well along with http calls. If your version is below Angular 4.3, follow below code for passing header.


const headers = new Headers();
headers.set('authentication', 'auth ticket');
const options = new RequestOptions({ headers: headers });

We are done. In this article we have discussed about passing data as FormData using httpClient.

Angular 2(+)Angular 4/5FormDatahttpClient

Related Info

1. Angular 2/5 routing with simple examples.

2. Rating star component using Angular.

1 comment :