×

AngularJS Tutorial

AngularJs Questions

AngularJS Practice

Advertisement


Angular - Fetch Data from API using HttpClient

By IncludeHelp Last updated : September 14, 2024

In this article, we have given an API with some dummy data, and our task is to fetch data from that API using HTTP and display it. We will use a case where the API contains user details, which we will fetch. The API is a fake API in which data is stored as a JSON format (Key: Value) pair.

Before proceeding with the main topic, let's briefly discuss API. An API stands for Application Programming Interface, which is a software intermediary that allows two applications to communicate with each other.

Angular offers an HttpClient module, which is used to communicate with the server and helps to send various requests to the server. We will also use the web restful services that provide accessibility to all CRUD operations such as "Create", "Read", "Update", and "Delete".

How to Fetch Data from API using HttpClient in Angular?

To fetch/read the data from API using HttpClient, we will use the get() method and subscribe() the data within the template to access it.

Following is the syntax of the get() method:

http.get(URL)

Steps to Fetch Data from API using HttpClient

Below is the steps (list of the important points) that you should remember while working with web rest services as follows:

1. Import HttpCliendModule Module

Make sure the HttpCliendModule must be imported within the parent module.

Here is the code:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
@NgModule({
 declarations: [
   AppComponent,
   DashboardComponent,
 ],
 imports: [
   BrowserModule,
   AppRoutingModule,
   ReactiveFormsModule,
   HttpClientModule,
   FormsModule,
   RouterModule,
  
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

2. Import HttpClient module within service.ts file

Now, import the HttpClient module within the service.ts file:

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

@Injectable({
 providedIn: 'root'
})

export class AuthService {
 constructor(private http: HttpClient) { }
 baseURL: any = "http://localhost:3000/users";
 getAllData(){
   return this.http.get(this.baseURL);
 }
}

3. Write Code to Fetch Data from API

Use the following snippet of code to fetch the data from API:

this.auth.getAllData().subscribe(res=>{
   this.allData = res;
});

Complete Code to Fetch Data from API using HttpClient (With All Files)

Now let's see the complete guide on how to fetch API data using the Angular HttpClient module as follows:

File: component.html

This is a template where we will display the fetched data:

<h1>API Data Using HttpClient</h1>
<ul *ngFor="let d of allData">
   <li>{{d.id}}</li>
   <li>{{d.name}}</li>
   <li>{{d.age}}</li>
   <li>{{d.city}}</li>
   <li>{{d.email}}</li>
   <li>{{d.gender}}</li>
</ul>

File: component.ts

This is a typescript file where we will subscribe the data, fetch the data, and store it in a given variable as follows:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../Services/auth.service';

@Component({
 selector: 'app-dashboard',
 templateUrl: './dashboard.component.html',
 styleUrl: './dashboard.component.css'
})
export class DashboardComponent implements OnInit{
 constructor(private auth: AuthService){}
 allData: any;
ngOnInit(): void {
 this.auth.getAllData().subscribe(res=>{
   this.allData = res;
 });
}
}

File: service.ts

This is a service_name file where we will perform all the HttpClient and RestFul web services to fetch the API data as follows:

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

@Injectable({
 providedIn: 'root'
})

export class AuthService {
 constructor(private http: HttpClient) { }
 baseURL: any = "http://localhost:3000/users";

 getAllData(){
   return this.http.get(this.baseURL);
 }
}

Note: You must have the active or currently running URL where API data were present, or you will have the .json file in your assets folder:

Output

As we have done all the steps on how to fetch the data from the API, let's the output:

Fetch Data from API using HttpClient

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.