Angular Http Client Module Example
Welcome readers, in this tutorial, we will learn about the Http Client Module to interact with the restful endpoints.
1. Introduction
In 2K17, Angular 6 framework introduced the Http Client Module to fetch the data from the restful endpoints. This module,
- Allows developers to send HTTP requests or make API calls to the external servers
- Replaces the old Http Client and is available in the
@angular/common/http
package - An abstract to
XMLHttpRequest
interface and provides new features like – Request and Response Interceptors, Observables, Better testing support, and error handling, etc.
Now open the visual studio code and let us see how to implement this tutorial in angular 6 frameworks.
2. Angular Http Client Module Example
Here is a systematic guide for implementing this tutorial.
2.1 Tools Used
We are using Visual Studio Code and Node Terminal to compile and execute the angular code on a browser.
2.2 Project Structure
In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the angular application.
3. Creating Angular application
Run the ng new angular-httpclient-tutorial
command in the npm console to create a new angular project. Once the new project is created, following the below steps.
3.1 Import Http Client module
To start working we will need to import the HttpClientModule
module in src/app/app.module.ts
file.
app.module.ts
// Injecting http client module in the angular application. import { HttpClientModule } from '@angular/common/http'; // Declaring the http client module in the imports section of NgModule decorator. imports: [ BrowserModule, HttpClientModule ],
3.2 Creating a Service
To start using the Http Client Module in our application, we will need to create a service. Run the ng g s service/newsservice
command in the npm console to create a news service. This service,
- Will use the
HttpClient
to send the HTTP requests - Will be injected in our application to perform the HTTP operations
Make note, users’ needs to generate a new token for serving the requests from the newsapi.org!
newsservice.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class NewsserviceService { constructor(private _http: HttpClient) { } // Service method to fetch the top news headlines. getHeadlines() { console.log('Fetching top headlines from the server.'); let apitoken = "72eb33ec969544a0af14de32981747cc"; return this._http.get("https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=" + apitoken); } }
3.3 Creating Model
To start using the Http Client, we will inject the news service in our component model.
app.component.ts
import { Component } from '@angular/core'; import { NewsserviceService } from './service/newsservice.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular HttpClient Tutorial'; // Variable to store the response for the news headline. news: any; constructor(private _serv: NewsserviceService) {} // Angular method to fetch the news headlines. getNews() { this._serv.getHeadlines().subscribe(res => { this.news = res; }); } }
3.4 Creating Component
To view the data fetched from the service we will need to update the HTML view where we will render the news array.
app.component.html
<html> <head> <link rel="stylesheet" href="https://www.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9zdGFja3BhdGguYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.3.1/css/bootstrap.min.css"> </head> <body> <!--The content below is only a placeholder and can be replaced.--> <div class="container"> <h2 class="text-info text-center">{{ title }}!</h2> <hr /> <div id="submit_btn"> <button type="button" class="btn btn-outline-primary" (click)="getNews();">Get News</button> </div> <div> </div> <div *ngIf="news"> <table id="table" class="table table-bordered"> <thead> <th>#</th> <th>Source</th> <th>Title</th> <th>Description</th> <th>Author</th> <th>Time</th> </thead> <tbody> <tr *ngFor="let a of news.articles; let i=index"> <td>{{i+1}}</td> <td>{{a.source.name}}</td> <td>{{a.title}}</td> <td>{{a.description}}</td> <td>{{a.author | titlecase}}</td> <td>{{a.publishedAt | date:'medium'}}</td> </tr> </tbody> </table> </div> </div> </body> </html>
4. Run the Application
As we are ready with all the changes, let us compile and run the angular application with ng serve
command. Once the projects are successfully compiled and deployed, open the browser to test it.
5. Project Demo
Open your favorite browser and hit the angular application url (http://localhost:4200/
) to display the index page of the application.
Users can click the button to fetch the top news headlines as shown in Fig. 3.
That is all for this tutorial and I hope the article served you whatever you were expecting for. Happy Learning and do not forget to share!
6. Conclusion
In this section, we learned how to create a simple Http Client Module application. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was a tutorial of Http Client Module in the angular framework.
You can download the full source code of this example here: Angular Http Client Module Example