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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Palak Sharma
Palak is enthusiastic and passionate about coding , Her areas of expertise in coding languages are JavaScript and angular , html and css .