Server Communication In Angular using HTTP Client

Posted By : Palak Sharma | 23-Sep-2017

Http Client Module is introduced in Angular 4 , this is a former implementation of Http Module . The HttpClient service is a part of  Http Client Module only and it is used to intiate requests from server and process response with your application.

To use HttpClientService in our module , first we need to import HttpClientModule in our application. For eg:-

 
import{HttpClientModule} from '@angular/common/http';

Once imported we can use HttpClient in our components , all we need to do is to inject into the class constructor. For eg:-

 
import {HttpClient} from '@angular/common/http';
constructor(private http:HttpClient){}
 

To execute request HttpClient will use XMLHttpRequest browser API to get the response. For eg:-

 
ngOnInit(){
this.http.get('http://jsonplaceholder.com/users').subscribe(success=>{
  console.log(success);
});
}

The output will directly access the JSON repsonse by subscribing the response which we get from the api. 

 

Error Handling:-

A HttpRequest can fail , for various reasons , so to handle error case in our module , we have to add second callback method to subscribe. For eg:-

 
 
ngOnInit(){
this.http.get('http://jsonplaceholder.com/users').subscribe(
success=>{
  console.log(success);
},
error=>{
console.log(error);
}
});
}
 

To summarize , HttpClient module is used to fetch the api from service and subscribe the method and get the response in return from respective api's.

About Author

Author Image
Palak Sharma

Palak is enthusiastic and passionate about coding , Her areas of expertise in coding languages are JavaScript and angular , html and css .

Request for Proposal

Name is required

Comment is required

Sending message..