The Web applications communicate with backend
services over the HTTP/HTTPS protocol and the browsers support to the XMLHttpRequest interface and the fetch () API to execute HTTP request.
The new HttpClient
service is included in the HttpClientModule
and it used to initiate HTTP request
and responses in angular apps.
The HttpClient
is more modern and easy to use alternative of HTTP.
Also the HttpClient
is use the XMLHttpRequest browser
API to execute HTTP request and it specific the HTTP request type’s i.e.
ü Get()
ü Post()
ü Put()
ü Delete()
ü Patch()
ü Head()
ü Jsonp()
Before use the HttpClient, we need to import in the HttpClientModule into your AppModule. Once you import HttpClientModule into your AppModule, you can inject HttpClient into your components and services.
HttpClientModule -
The HttpClientModule imported form -
import
{ HttpClientModule } from
'@angular/common/http';
NgModule which provides the HttpClient
and associated with components services and the interceptors can be added to
the chain behind HttpClient by binding them to the multi provider for
HTTP_INTERCEPTORS.
HttpClient – The HttpClient is used to perform HTTP requests.
The HttpClient imported form -
import
{ HttpClient } from
'@angular/common/http';
Example for the get () and post ()
method on HttpClient –
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
baseUrl ="https://code-sample.com/";
users = null;
// Inject HttpClient into your
component or service.
constructor(private http: HttpClient){ }
//Load User info.
ngOnInit(): void {
// Make the HTTP
request:
this.http.get(this.baseUrl +'api/users/').subscribe(data => {
this.users = data;
},
err => {
console.log("Error-
something is wrong!")
});
}
addUser = function(){
let user ={
id: 1,
name: 'Anil Singh',
user_Id:9979,
site : 'https://code-sample.com'
}
//Make the HTTP Post Request
this.http.post(this.baseUrl +'api/addUser/', user)
.subscribe(
result => {
console.log("The User
added successfully!");
console.log(result);
},
err => {
console.log("Error-
something is wrong!")
});
}
}
I hope you are enjoying with this post!
Please share with you friends!! Thank you!!!