AngularJS Fetch Data From API using HttpClient - GeeksforGeeks (2024)

Last Updated : 19 Oct, 2023

Summarize

Comments

Improve

There is some data in the API and our task here is to fetch data from that API using HTTP and display it. In this article, we will use a case where the API contains employee details which we will fetch. The API is a fake API in which data is stored in the form of a JSON (Key: Value) pair.

API stands for Application Programming Interface, which is a software intermediary that allows two applications to communicate with each other.Angular offers HttpClient to work on API and handle data easily. In this approach HttpClient along with subscribe() method will be used for fetching data. The following steps are to be followed to reach the goal of the problem.

  • Step 1: Create the necessary component and application.
  • Step 2: Do the necessary imports for HttpClient in the module.ts file.
import { HttpClientModule } from '@angular/common/http';

@NgModule({
declarations: [
],
imports: [
HttpClientModule,
],
providers: [],
bootstrap: []
})

  • Step 3: Do the necessary imports for HttpClient in the component.ts file.
import { HttpClient } from '@angular/common/http';

export class ShowApiComponent implements OnInit {
constructor(private http: HttpClient) {
...
}
}

  • Step 4: We get Response from API by passing the API URL in get() method and then subscribing to the URL.
this.http.get('API url').subscribe(parameter)

The Response of the API is stored in a variable from which data can be accessed.

  • Step 5: Now data array needs to be shown using HTML. A Table is used in which rows are added dynamically by the size of the data array. For this, rows are created using *ngFor then data is shown from each row.

Prerequisite: Here you will need an API for getting data. A fake API can also be created and data can be stored.

Note: We can use any API link in place of (http://…com).

Example: Here, for example, we already have a fake API that contains employee data that we will fetch

Steps to Display the Data:

  • Step 1: Required Angular App and Component(Here show-api component) is created
  • Step 2: For using HttpClient for our app, HttpClientModule is imported to app.module.ts

app.module.ts:

Javascript

import { BrowserModule }

from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { HttpClientModule }

from '@angular/common/http';

import { AppRoutingModule }

from './app-routing.module';

import { AppComponent } from './app.component';

import { AddInputComponent }

from './add-input/add-input.component';

import { ShowApiComponent }

from './show-api/show-api.component';

@NgModule({

declarations: [

AppComponent,

ShowApiComponent

],

imports: [

BrowserModule,

AppRoutingModule,

HttpClientModule

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule { }

  • Step 3: In the Typescript file of the component(Here show-api.component.ts) import HttpClient. HttpClient helps to render and Fetch Data. The Employee Details API is used to get data. We get Response from API by passing the API url in get() method and then subscribing to the URL. The Response of the API is stored in a variable named li from which the data array is further stored in an array named list here. The list array will help us show the data. A user-defined function is called when the response comes to hide the loader.

show-app.component.ts:

Javascript

import { Component, OnInit } from '@angular/core';

import { HttpClient } from '@angular/common/http';

@Component({

selector: 'app-show-api',

templateUrl: './show-api.component.html',

styleUrls: ['./show-api.component.css']

})

export class ShowApiComponent implements OnInit {

li: any;

lis = [];

constructor(private http: HttpClient) {

}

ngOnInit(): void {

this.http.get(

.subscribe(Response =& gt; {

// If response comes hideloader() function is called

// to hide that loader

if (Response) {

hideloader();

}

console.log(Response)

this.li = Response;

this.lis = this.li.list;

});

function hideloader() {

document.getElementById('loading').style.display = 'none';

}

}

}

// The url of api is passed to get() and then subscribed and

// stored the response to li element data array list[] is created

// using JSON element property

  • Step 4: Now data array needs to be shown using HTML. A Table is used in which rows are added dynamically by the size of the data array. For this, rows are created using *ngFor then data is shown from each row. In this file, added a loader that loads till the response comes.

show-app.component.html:

HTML

<h1>Registered Employees</h1>

<div class="d-flex justify-content-center">

<div class="spinner-border" role="status">

<span class="sr-only" id="loading">

Loading...

</span>

</div>

</div>

<table class="table" id='tab'>

<thead>

<tr>

<th scope="col">Name</th>

<th scope="col">Position</th>

<th scope="col">Office</th>

<th scope="col">Salary</th>

</tr>

</thead>

<tbody>

<tr *ngFor="let e of lis;">

<td>{{ e.name }}</td>

<td>{{ e.position }}</td>

<td>{{ e.office }}</td>

<td>{{ e.salary }}</td>

</tr>

</tbody>

</table>

Output: In the console, the data array of the response can also be seen which is further used to show data:

AngularJS Fetch Data From API using HttpClient - GeeksforGeeks (1)



taran910

AngularJS Fetch Data From API using HttpClient - GeeksforGeeks (3)

Improve

Next Article

How to fetch data from an API in ReactJS ?

Please Login to comment...

AngularJS Fetch Data From API using HttpClient - GeeksforGeeks (2024)
Top Articles
Cloud Logging | Google Cloud | Google Cloud
How To Get Your Ex Back When He Has Moved On To a New Girlfriend
Will Byers X Male Reader
Encore Atlanta Cheer Competition
Duralast Gold Cv Axle
Blanchard St Denis Funeral Home Obituaries
Federal Fusion 308 165 Grain Ballistics Chart
Stl Craiglist
Lichtsignale | Spur H0 | Sortiment | Viessmann Modelltechnik GmbH
The Many Faces of the Craigslist Killer
Revitalising marine ecosystems: D-Shape’s innovative 3D-printed reef restoration solution - StartmeupHK
Readyset Ochsner.org
Dc Gas Login
WEB.DE Apps zum mailen auf dem SmartPhone, für Ihren Browser und Computer.
Lazarillo De Tormes Summary and Study Guide | SuperSummary
Pretend Newlyweds Nikubou Maranoshin
Msu 247 Football
PowerXL Smokeless Grill- Elektrische Grill - Rookloos & geurloos grillplezier - met... | bol
Today Was A Good Day With Lyrics
Nz Herald Obituary Notices
Www Pointclickcare Cna Login
Pawn Shop Moline Il
Acurafinancialservices Com Home Page
Cowboy Pozisyon
Tinyzonehd
Jackass Golf Cart Gif
Himekishi Ga Classmate Raw
49S Results Coral
Fairwinds Shred Fest 2023
404-459-1280
De beste uitvaartdiensten die goede rituele diensten aanbieden voor de laatste rituelen
Tendermeetup Login
Unity Webgl Player Drift Hunters
Google Chrome-webbrowser
Blasphemous Painting Puzzle
Saybyebugs At Walmart
Gateway Bible Passage Lookup
The best bagels in NYC, according to a New Yorker
Bekah Birdsall Measurements
Differential Diagnosis
844 386 9815
Go Nutrients Intestinal Edge Reviews
Huntsville Body Rubs
Headlining Hip Hopper Crossword Clue
Benjamin Franklin - Printer, Junto, Experiments on Electricity
Strange World Showtimes Near Century Federal Way
Denys Davydov - Wikitia
When Is The First Cold Front In Florida 2022
Ocean County Mugshots
What Are Routing Numbers And How Do You Find Them? | MoneyTransfers.com
Kindlerso
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 5986

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.