AngularJS Fetch Data From API Using HttpClient
AngularJS Fetch Data From API Using HttpClient
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.
@NgModule({
declarations: [
],
imports: [
HttpClientModule,
],
providers: [],
bootstrap: []
})
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.
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 { }
show-app.component.ts:
Javascript
}
ngOnInit(): void {
this.http.get(
'http://...com')
.subscribe(Response =& gt; {
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>