Angular HTTP Data Fetch

In the previous article, we’ve learned about HTTP and Observables in Angular. We’ve also learned about HTTP requests and HTTP response mechanisms in the previous article with block diagrams.

Angular Fetch Data from API Using HttpClientModule

In this article, we will see how to fetch data using HTTP and use it in our app. This part plays an important role when you’re working with real-life apps.

Let’s follow the below steps and understand how to fetch data by making HTTP calls and process the data.

NOTE: The prerequisite for this article is the concept of Angular services and how to deal with them.

Step 1: Add HttpClientModule Into the Imports Array and Import It

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from "@angular/common/http";
import { ServicesService } from './services.service';

@NgModule({
  declarations: [
    AppComponent,
  ],

  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [ServicesService],
  bootstrap: [AppComponent]
})

export class AppModule { }
  • Add HttpClientModule into the imports array.
  • Import HttpClientModule from @angular/common/http.

Step 2: Create an Instance of HttpClient and Fetch the Data Using It

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { IStudents } from './student';

@Injectable({
  providedIn: 'root'
})

export class StudentService {
  url="/assets/data/students.json";
  constructor(private http:HttpClient) { }

  getStudents():Observable <IStudents[]> {
    return this.http.get<IStudents[]>(this.url);
  }
}

NOTE: We made a students.json file inside the assets folder, which consists of data and works as api_url for us.

[
  {"id":100, "name":"Rahul", "Gender":"Male", "age":20},
  {"id":101, "name":"Anish", "Gender":"Male", "age":20},
  {"id":102, "name":"Manju", "Gender":"Female", "age":20},
  {"id":103, "name":"Rohan", "Gender":"Male", "age":20}
]

Step 3: Create a Student Interface To Cast the Observables

export interface IStudents {
    id:number,
    name:string,
    gender:string,
    age:number
}

Create a new ts file to create the interface.

Step 4: Subscribe the Data From the Service in the Component

import { Component,OnInit } from '@angular/core';
import { StudentService } from './student.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  title = 'my-app';
  students = []
  constructor(private studentservice:StudentService) { }

  ngOnInit():void {
    this.studentservice.getStudents().subscribe(data => {
      console.log(data)
    })
  }
}

Output:

angular http data fetch example

We’ve printed the data in the console. The data can also be stored in an empty array and use in the component as per requirements.

Conclusion

We hope this article has helped you understand how to fetch data from a web server and use it in the various components. This is the most important part of any real-life project you’re working on. In the next article, we’ll learn HTTP error handling as well.

Read Next: Angular HTTP Error Handling

Leave a Reply

Your email address will not be published. Required fields are marked *