How To Use HttpClient With Example In Angular 9

In this article, we’ll see how to use HttpClient to build a service for fetching data in your Angular application from a REST API server.
 
We’ll see how to implement an Angular service to encapsulate the code that handles fetching data from the REST API server.
 
An Angular service is simply a TypeScript class that you can inject in other services or components using the Angular dependency injector.
 
Prerequisites
 
You need to have Node, NPM and Angular CLI and initialize an Angular project.
 
Step 1 - Importing HttpClient Module
 
Open the src/app/app.module.ts file and update as follows,
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module';  
  3. import { AppComponent } from './app.component';  
  4. import { HttpClientModule } from '@angular/common/http';  
  5. import { AppComponent } from './app.component';  
  6. import { HttpClientModule } from '@angular/common/http';@NgModule({  
  7.    declarations: [  
  8.    AppComponent,  
  9. ],  
  10. imports: [  
  11.    BrowserModule,  
  12.    AppRoutingModule,  
  13.    HttpClientModule  
  14. ],  
  15. providers: [],  
  16.    bootstrap: [AppComponent]  
  17. })  
  18. export class AppModule { }  
  19.    declarations: [  
  20.       AppComponent,  
  21. ],  
  22. imports: [  
  23.    BrowserModule,  
  24.    AppRoutingModule,  
  25.    HttpClientModule  
  26. ],  
  27. providers: [],  
  28.    bootstrap: [AppComponent]  
  29. })  
  30. export class AppModule { }  
Step 2 - Creating an Angular Service
 
Open a new terminal and run the following command,
 
$ ng generate service backend
 
Step 3 - Importing and Injecting HttpClient
 
Open the src/app/backend.service.ts file, then import and inject HttpClient as follows,
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';@Injectable({  
  3.    providedIn: 'root'  
  4.    })  
  5.    export class BackendService { constructor(private httpClient: HttpClient) { }  
  6. }  
We import HttpClient and inject it via the service constructor.
 
Step 4 - Defining a Method for Sending HTTP Requests
 
Next, define a get() method for sending a GET request to the server for fetching data,
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';@Injectable({  
  3.    providedIn: 'root'  
  4. })  
  5. export class BackendService { constructor(private httpClient: HttpClient) { } public get(){  
  6.    return this.httpClient.get("http://server.com/endpoint");  
  7.    }  
  8. }  
We call the get() method of HttpClient to send a GET request to the REST API server.
 
Step 5 - Creating an Angular Component
 
Head back to your terminal and run the following command to generate a component named home,
 
$ ng generate component home
 
Step 6 - Injecting the Angular Service
 
Go to the src/app/home/home.component.ts file, import and inject the backend service as follows,
  1. import { Component, OnInit } from '@angular/core';  
  2. import { BackendService } from '../backend.service';@Component({  
  3.    selector: 'app-home',  
  4.    templateUrl: './home.component.html',  
  5.    styleUrls: ['./home.component.css']  
  6. })  
  7. export class HomeComponent implements OnInit { data= []; constructor(private backendService: BackendService) { }}  
Step 7 - Calling the Service Method
 
Finally, we can call the get() method of the service to send a GET request as follows,
  1. ngOnInit() { this.backendService.get().subscribe((ret: any[])=>{  
  2.    console.log(ret);  
  3.    this.data = ret;  
  4.    })  
  5. }  
Step 8 - Displaying Data with ngFor
 
Next, open the src/app/home/home.component.html file and update it as follows,
  1. <div>  
  2.    <ul>  
  3.       <li *ngFor="let item of data">  
  4.          {{item.name}}  
  5.       </li>  
  6.    </ul>  
  7. </div>  
Here, we suppose that our data elements have a name attribute.
 

Conclusion

 
In this how-to post, we’ve seen how to create a service in Angular and use HttpClient to send HTTP requests to REST API backends and finally display the data returned from the API using the ngFor directive.


Similar Articles