Friday, 16 March 2018

Http calls in Angular using HttpClient.

Angular 4.3(+)Angular 5HttpHttpClient

In this article we are going to discuss about making http calls using HttpClient. HttpClient is supported by Angular 4.3 version onwards. In my previous article I wrote about doing the same using http that can be used for angular version less than 4.3. Let us check the methods one by one.

1. Post
2. Get
3. Delete
4. Put

Post


Let us check HttpClient post call with one example. Create a component and invoke the method in the service file for making an API call, response will be returned to component.

Component


sendData() {
    this.item = {
      name: 'Angular',
      type: 'Framework',
      parent: 'Javascript'
    }

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

CommonService is our service file, where we will be making the API call. Under data we will be getting the response and error in error block. Now let us check service code.

Service


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, JSON.stringify(item))
      .map((response: Response) => {
        return response;
      });

  }
}

Here we have imported HttpClient and map from rxjs. To make it work you need to import HttpClientModule in the module file and also add under @NgModule/imports. Make sure you import after BrowserModule to make it work. I will share the module code as well at the end of the article. Now let us check the get call.

Get


Check the code below.

Component


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

Service


getData() {
    this._url = '/api/get/data';
    return this.http.get(this._url)
      .map((response: Response) => {
        return response;
      })

  }

It is almost same except we are not passing the data.

Delete


It is also almost same, check below code.

Component


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

Service


deleteData() {
    this._url = '/api/delete/id';
    return this.http.delete(this._url)
      .map((response: Response) => {
        return response;
      })
  }

Put


Put we use to update data, while post for adding new data.

Component


sendDataUsingPut() {
    this.item = {
      name: 'Angular',
      type: 'Framework',
      parent: 'Javascript'
    }

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

  }

Service


sendDataUsingPut(item) {
    this._url = '/api/add/data';
    return this.http.post(this._url, JSON.stringify(item))
      .map((response: Response) => {
        return response;
      });
  }

Now check our module code.

Module



import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

//Services
import { CommonService } from './services/common.service';

@NgModule({
  declarations: [
    AppComponent,
    GeneralComponent,
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
  ],
  providers: [CommonService],
  bootstrap: [AppComponent]
})
export class AppModule { }

We have imported HttpClientModule and also added CommonService in provider.

We are done. In this article we have discussed about making an API call using HttpClient. This is supported by Angular 4.3 version onwards.

Angular 4.3(+)Angular 5HttpHttpClient

Related Info

1. Angular 2/5 routing with simple examples.

2. Rating star component using Angular.

No comments :

Post a comment