Angular Observables and Subscribers

  • Observables are used for event handling, asynchronous programming, and handling multiple values.
  • Observables are declarative, means consumers has to subscribe for observables to receive asynchronous data as and when updated in the backend and receives updated data until it was unsubscribed.

Steps to create Observables and Subscribe to it

  1. We need data to know Observable behaviour in Angular Page. We can either create a JSON REST Service in Spring, .Net Web API, PHP etc., which fetches data from DB. Here I am creating courses.json static file to simulate Observables functionality and keeping in /assets/data/ folder.
  2. Create the Interface. Here I have created the ICourses Interface.
  3. In app.module.ts file, Import HttpClientModule from @angular/common/http and add HttpClientModule under imports.
  4. Create the CoursesService which has the CRUD operations.
    • Import Observable from rxjs.
    • Import HttpClient from @angular/common/http.
    • Import ICourses interface.
    • Inject HttpClient in the CoursesService Constructor
    • Create getCourses() Method which returns Observable of type ICourses.
  5. In app.component.ts, Inject the CoursesService in the AppComponent Constructor. Inside ngOnInit() method, call the getCourses() method of the CoursesService and Subscribe to it.

courses.json

[
{"id":1,"course":"Python", "duration":30},
{"id":2,"course":"Java", "duration":45},
{"id":3,"course":"Angular", "duration":25},
{"id":4,"course":"R", "duration":35},
{"id":5,"course":"Data Science", "duration":45},
{"id":6,"course":"Git", "duration":10},
{"id":7,"course":"AWS", "duration":20},
{"id":8,"course":"SQL Server", "duration":40},
{"id":9,"course":"MongoDB", "duration":20},
{"id":10,"course":"Spring Framework", "duration":45},
{"id":11,"course":"My SQL", "duration":45},
{"id":12,"course":"PostgreSQL", "duration":30}  ,
{"id":13,"course":"TypeScript", "duration":10}
]

courses.ts (Interface)

export interface ICourses {
    id: number;
    course: string;
    duration: number;

}

app.module.ts

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';

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

courses.services.ts (Service)

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';  
import { Observable } from 'rxjs'; 
import {ICourses} from './courses';

@Injectable({
  providedIn: 'root'
})
export class CoursesService {

  constructor(private http:HttpClient) { }  
  
  private _url:string = "/assets/data/courses.json";

  getCourses(): Observable<ICourses[]> {
    return this.http.get<ICourses[]>(this._url);
  }

 
}

app.component.ts

import { Component, OnInit } from '@angular/core';
import {CoursesService} from './courses.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'myapp';
  public courses = [];
  constructor(private _courseService:CoursesService) { }  

 ngOnInit(){
   this._courseService.getCourses()
   .subscribe(data => this.courses = data, err => console.error('Observer got an error: ' + err),
   () => console.log('Observer got a complete notification'));

 }
}

app.component.html

<div>
<h2>Courses List</h2>
  <ul *ngFor=" let x of courses"><li>{{x.course}}</li></ul>
</div>

Check our other Angular Tutorials at Angular Tutorials

References

  • https://angular.io/guide/observables

Learn more about Angular features in the next upcoming blog articles.

Happy Learning!