HTTP And Observables In Angular

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 what an 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.

Data array

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

HTTP

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 employees and return it to the subscribed component. HTTP is just a two-way process, the first is to send the request and the second is to receive the response.

The web API/service or the database is only responsible for giving 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, and the name of the students, whereas the Student Marks component will display the ID and 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 in 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 the below contents,

Import the HttpClientModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { StudentDetailsComponent } from './student-details/student-details.component';
import { StudentMarksComponent } from './student-marks/student-marks.component';
import { StudentService } from './student.service';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    StudentDetailsComponent,
    StudentMarksComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [StudentService],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

Add the below contents under students.json.

[
    {"id": 1001, "name": "Irshad", "marks": 90},
    {"id": 1002, "name": "Imran", "marks": 80},
    {"id": 1003, "name": "Rahul", "marks": 70},
    {"id": 1004, "name": "Ajay", "marks": 85},
    {"id": 1005, "name": "Sunny", "marks": 60}
]

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 the app directory and add the below contents.

export interface IStudent {
  id: number;
  name: string;
  marks: number;
}

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

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

@Injectable()
export class StudentService {

  private url: string = '/assets/AppData/students.json';

  constructor(private http: HttpClient) { }
  
  getStudents(): Observable<IStudent[]> {
    return this.http.get<IStudent[]>(this.url);
  }
}

You can also use ‘any’ in the observable cast.

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

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

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

@Component({
  selector: 'app-student-details',
  templateUrl: './student-details.component.html',
  styleUrls: ['./student-details.component.css']
})
export class StudentDetailsComponent implements OnInit {

  public students = [];

  constructor(private studentService: StudentService) { }

  ngOnInit() {
    this.studentService.getStudents().subscribe(data => this.students = data);
  }
}

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

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

@Component({
  selector: 'app-student-marks',
  templateUrl: './student-marks.component.html',
  styleUrls: ['./student-marks.component.css']
})
export class StudentMarksComponent implements OnInit {

  public students = [];

  constructor(private studentService: StudentService) { }

  ngOnInit() {
    this.studentService.getStudents().subscribe(data => this.students = data);
  }
}

Run the application,

Angular 3

What we have done,

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