HTTP And Observables In Angular

Using HTTP in Angular we are going to fetch data from the web server, We will make a call to the web server that will in return provides data. For better understanding this process we need to know what is HTTP call and what is observable that is returned from the HTTP call.

Introduction

Using HTTP in Angular we are going to fetch data from the web server. We will make a call to the web server that will in return provide data. For a better understanding of this process, we need to know that what HTTP call is, as well as what is observable that is returned from the HTTP call.

Prerequisites

  • HTML, CSS and JS
  • Basics of TypeScript.

Note
See my previous article “Services in Angular” and create the Application using services.

So far what we have done is to give the data array that has some values directly to the component.

HTTP And Observables In Angular 

Now, what we need to achieve is to return the same data but with the help of HTTP.

HTTP And Observables In Angular 

In the above diagram, the studentService will call or make the HTTP request from the HTTP module. This HTTP request will hit the web API or service that will in return fetch the data from the database and send it back as an HTTP response. This response that we are getting from the HTTP is nothing but the observable. Now the observable needs to be cast to the particular type and the studentService will cast this observable data to the array of employee and return it to the subscribed component. HTTP is just a two-way process, first is to send the request and second is to receive the response.

The web API/service or the database is only responsible to give the data and their job is done.

HTTP response is nothing but the Observable returned by HttpClient.get

Components subscribe to the service and receive and operate the data accordingly. Student Details may only display id, the name of the students, whereas Student Marks component will display id, marks of the students.

How it works,

  • Make a request from StudentService.
  • Get the observable and cast it.
  • Subscribe the observable to the components.
  • Store it to the local variables to make it useful in your component.

Let us start using the HTTP functionality.

Open your application.

Open app.module.ts and add below contents,

Import the HttpClientModule.

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import {FormsModule} from '@angular/forms';  
  4. import { AppComponent } from './app.component';  
  5. import { StudentDetailsComponent } from './student-details/student-details.component';  
  6. import { StudentMarksComponent } from './student-marks/student-marks.component';  
  7. import { StudentService } from './student.service';  
  8. import { HttpClientModule } from '@angular/common/http';  
  9.   
  10. @NgModule({  
  11.   declarations: [  
  12.     AppComponent,  
  13.     StudentDetailsComponent,  
  14.     StudentMarksComponent  
  15.   ],  
  16.   imports: [  
  17.     BrowserModule,  
  18.     HttpClientModule  
  19.   ],  
  20.   providers: [StudentService],  
  21.   bootstrap: [AppComponent]  
  22. })  
  23. export class AppModule { }  

Create json file on location ‘/assets/AppData/students.json’.

Add the below contents under students.json

  1. [  
  2.     {"id" : 1001, "name" : "Irshad""marks" : 90},  
  3.     {"id" : 1002, "name" : "Imran""marks" : 80},  
  4.     {"id" : 1003, "name" : "Rahul""marks" : 70},  
  5.     {"id" : 1004, "name" : "Ajay""marks" : 85},  
  6.     {"id" : 1005, "name" : "Sunny""marks" : 60}  
  7. ]  

Right now we are using the JSON file to get the data. When the data will come from web API or services then we just need to change the requesting URL.

Add a file (aks interface) student.ts under app directory and add the below contents,

  1. export interface IStudent {  
  2.     id: number,  
  3.     name: string,  
  4.     marks: number  

Open student.service.ts and add the below contents,

  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3. import { IStudent } from './student';  
  4. import { Observable } from 'rxjs';  
  5.   
  6. @Injectable()  
  7. export class StudentService {  
  8.   
  9.   private url : string ='/assets/AppData/students.json';  
  10.   
  11.   constructor(private http: HttpClient) { }  
  12.   getStudents() : Observable<IStudent[]>{  
  13.     return this.http.get<IStudent[]>(this.url);  
  14.   }  
  15. }  

You can also use ‘any’ in observable cast.

  1. getStudents() : Observable<any[]>{  
  2.     return this.http.get<any[]>(this.url);  
  3.   }  

Open student-details.component.ts and add the below contents,

  1. import { Component, OnInit } from '@angular/core';  
  2. import { StudentService } from '../student.service';  
  3.   
  4. @Component({  
  5.   selector: 'app-student-details',  
  6.   templateUrl: './student-details.component.html',  
  7.   styleUrls: ['./student-details.component.css']  
  8. })  
  9. export class StudentDetailsComponent implements OnInit {  
  10.   
  11.   public students = [];  
  12.   constructor(private studentService : StudentService) {   
  13.   }  
  14.   
  15.   ngOnInit() {  
  16.     this.studentService.getStudents().subscribe(data => this.students = data);  
  17.   }  
  18. }  

Open student-marks.component.ts and add the below contents,

  1. import { Component, OnInit } from '@angular/core';  
  2. import { StudentService } from '../student.service';  
  3.   
  4. @Component({  
  5.   selector: 'app-student-marks',  
  6.   templateUrl: './student-marks.component.html',  
  7.   styleUrls: ['./student-marks.component.css']  
  8. })  
  9. export class StudentMarksComponent implements OnInit {  
  10.   
  11.   public students = [];  
  12.   constructor(private studentService : StudentService) {   
  13.   }  
  14.   
  15.   ngOnInit() {  
  16.     this.studentService.getStudents().subscribe(data => this.students = data);  
  17.   }  
  18.   
  19. }  

Run the application,

HTTP And Observables In Angular 

What we have done,

  1. Added HttpClientModule in our application.
  2. Injected this as a dependency injection in our studentService.
  3. Invoked the get method of from instance HTTP with proper URL. The get method returned the observable that we cast to IStudent array type.
  4. We have method getStudents() that will return the observable.
  5. The observable will not return any data until some component subscribes it.
  6. When we subscribe we get the data and assign it to the property in that component class and bind it to the HTML view.