Call API from Angular using Angular HTTPClient Library

Kailash Chandra Behera | Thursday, December 07, 2023

In my previous blog post, we discussed angular components. Here in this blog post (Call API from Angular using Angular HTTPCLIENT Library), guides and provide code for API call in Angular which will help you to call web API from angular application.

Getting Started

Angular provides a simplified client library based on XMLHTTPRequest interface, known as HTTPClient. This client library is available from @angular/common/http package. It can be imported in root module as below.

Why do use HTTPClient?

The manjor benefits of HTTPClient is listed below:

  • Provides typed request and response objects
  • Supports Observalbe APIs
  • Intercept request and response
  • Supports streamlined error handling
  • Contains testability features

How do use HTTPClient

To call API in angular or user the HTTPClient, just two steps is required that is

  1. Import HTTPClient
  2. Inject HTTPClient

Import HTTPClient

Open your app.module.ts file which is the root module of any angular application. If you have used multiple modules, then open the module file where you want to import the client module. The following is an example of importing in @NgModule.

 import { HttpClientModule } from '@angular/common/http';  
 @NgModule({  
  imports: [  
   BrowserModule,  
   // import HttpClientModule after BrowserModule.  
   HttpClientModule,  
  ],  
  ......  
  })  
  export class AppModule {}  

Call API Angular

Inject HTTPClient

The HTTPClient can be imported into component or in services. It is recommended to use Angular service to separate the Angular API call logic. Let's create a empService (empprofile.service.ts) as an example and defines get method of HttpClient:

 import { Injectable } from '@angular/core';  
 import { HttpClient } from '@angular/common/http';  
 const empLoginUrl: string = 'assets/data/emp.json';  
 @Injectable()  
 export class EmpProfileService {  
  constructor(private http: HttpClient) { }  
  getEmpProfile() {  
   return this.http.get(this.empLoginUrl);  
  }  
 }  

Angular API Call Example

The last step is use the created Angular service in component. The following code examples is subscribing the created service and invokes the service method.

 fetchEmpProfile() {  
  this.EmpProfileService.getEmpProfile()  
   .subscribe((data: emp) => this.emps= {  
     id: data['empid'],  
     name: data['firstName'],  
     city: data['city']  
   });  
 }  

Call API in Angular

Error Handling

The below code how to handle error If the request fails on the server or fails to reach the server due to network issues, then HttpClient will return an error object instead of a successful reponse. In this case, you need to handle in the component by passing error object as a second callback to subscribe() method.

 fetchEmpProfile() {  
  this.EmpProfileService.getEmpProfile()  
   .subscribe((data: emp) => this.emps= {  
     id: data['empid'],  
     name: data['firstName'],  
     city: data['city']  
   },  
 error => this.error = error);  
 }  

Call API from Angular

Read Full Response

The response body doesn't or may not return full response data because sometimes servers also return special headers or status code, which are important for the application workflow. To read the full response the HTTPClient provides observe option, the following example show how to read full response.

 getEmpResponse(): Observable<HttpResponse<Emp>> {  
  return this.http.get<Emp>(  
   this.empUrl, { observe: 'response' });  
 }  

Call API from Angular

Pass Headers to HTTPClient Angular

The HttpHeaders is used to pass headers to HTTPClient in Angular, the following code describes the same.

 constructor(private _http: HttpClient) {}  
 this._http.get('someUrl',{  
   headers: {'header1':'value1','header2':'value2'}  
 });  
 (or)  
  // create header object
 let headers = new HttpHeaders().set('header1', headerValue1);   
  // add a new header, creating a new object
 headers = headers.append('header2', headerValue2);
  // add another header
 headers = headers.append('header3', headerValue3);
  // create params object
 let params = new HttpParams().set('param1', value1);
  // add a new param, creating a new object
 params = params.append('param2', value2);  
 params = params.append('param3', value3);
 // add another param 
 return this._http.get<any[]>('someUrl', { headers: headers, params: params })  

Call API from Angular

Summary

Call API in angular is as easy as other techniques, in the above of this blog we say how to achieve the angula api call. I hope this post is helpful to you.

Thanks