Angular HttpClient
Written By: Avinash Malhotra
Updated on
Angular HTTPClient is a class available in Angular to use web services or Web APIs. Web APIs are used in frontend to communicate with backend. We can use http verbs like get, post, put, patch and delete for CRUD operations.
In Vanilla JS, there are two ways to use web api, AJAX and Fetch. AngularJS use $http service which internally use AJAX as that time fetch was not available. FETCH API comes with JS ES6.
There are two ways to use http services in Angular:
- Fetch API
- HttpClient
Fetch
Fetch API is one of the easiest way to use Web Services in both Angular and Vanilla JS. Fetch is Promise based, so syntax is less and comes with modern features, unlike AJAX which was event based and need more code to write.
using fetch api in angular
<!--app.component.ts-->
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
standalone: true,
imports:[],
templateUrl: './app.component.html',
styleUrl: './app.component.css',
})
export class AppComponent {
title = 'myApp';
data:any;
ngOnInit(){
fetch("https://fakestoreapi.com/products").then(i=>i.json()).then(i=>{
this.data=i;
console.table(this.data);
});
}
}
HttpClient
Angular use HttpClient service to fetch data across web server or API. HttpClient is use in service.ts file. In component, we need to use HttpClientModule to use service. The response from Web Server or API is always in the form of Observable. Observables are better choice as they make it easier to work with asynchronous data.
Create a service name web to communicate with web server. We have to use get or post in services itself. The return value from service will be added to component.
web.service.ts
In web.service.ts, use private http : HttpClient in constructor. Now create a function getData which will return a API. I the example below, i am using PINCODE API.
Use http.get for http get API.
<!--web.service.ts-->
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class WebService {
constructor( private http:HttpClient) { }
getData(){return this.http.get("https://api.postalpincode.in/pincode/110001") }
}
HttpClientModule
In app.component.ts, import web.service.ts first. Now import HttpClientModule in component. HttpClientModule was introduced in Angular 4. HttpClientModule supports features like interceptors, response typing and has better error handling.
<!--app.component.ts-->
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { WebService } from './web.service';
@Component({
selector: 'app-root',
standalone: true,
imports:[ CommonModule, HttpClientModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css',
providers:[WebService]
})
export class AppComponent {
title = 'myApp';
data:any;
constructor( private res: WebService){}
ngOnInit(){
// console.log(this.data.getData()); // Observable
this.data.getData().subscribe( res=>{
this.data=res;
this.data=this.data[0].PostOffice;
console.table(this.data);
})
}
}
Get data
To use HTTP Get Method in Angular, use http.get() method. First we need to define get in services. Create a function with return value http.get().
defined get in service
<!--web.service.ts-->
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class WebService {
constructor( private http:HttpClient) { }
getData(pin){return this.http.get(`https://api.postalpincode.in/pincode/${pin}`) }
}
use http get in component
<!--app.component.ts-->
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { WebService } from './web.service';
@Component({
selector: 'app-root',
standalone: true,
imports:[ CommonModule, HttpClientModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css',
providers:[WebService]
})
export class AppComponent {
title = 'myApp';
data:any;
pincode="";
constructor( private res: WebService){}
changeData(){
this.data.getData(this.pincode).subscribe( res=>{
this.data=res;
this.data=this.data[0].PostOffice;
})
}
}
get response in table
Print data by using ngFor loop in HTML Table row.
<!--app.component.ts-->
<h1>{{title}}</h1>
<h2>API Data</h2>
<form (ngSubmit)="changeData()>
<input type="search" name="pin" [(mgModel)]="pincode">
<button>Check</button>
</form>
<table>
<tr *ngFor="let i of data">
<td>{{i.Name}}</td>
<td>{{i.District}}</td>
<td>{{i.Division}}</td>
<td>{{i.State}}</td>
</tr>
</table>
Post data
To use Post Method, Angular use http.post() method
<!--web.service.ts-->
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class WebService {
constructor( private http:HttpClient) { }
postData(){
return this.post("https://domain.com/post", body, {headers}).subscribe(res=>{
this.data=res;
})
}
}