Menu

Angular Observables

April 5, 2020 - Frontend Development
Angular Observables

Surely there are hundreds of articles available online on the angular Observables. A lot of among them would focus on the theoritical aspects of it. But, there are times when a developer wouldn’t want to go through all the details specially when the implementation has to be quicker with a simpler understanding of the concept. Here I am focusing just on the obvious and the absolute essential concepts of implementing the angular Observables. Which primarily is enough to understand and implement an Observables.

Observables

Think of it as a wrapper around a data source where your data source is basically a stream of data. Now, this data can either be synchronous or asynchronous. As an instance the data could be coming from an external rest API.
Observables are typically used to handle asynchronous data. You kind of bind the Observable around the data source and when a new value is received from the source you have to define ways to handle it. Take a look at the diagram below:

Pic: Observables emitting a stream of data

An observable comes into action whenever a new value occurs. And this new value received from the data source has to be handle. This handling of new incoming data is handled by the Observer.

Observer

Observer are there to execute the code whenever a new value is received. There are three methods in an observers

  1. next()
  2. error()
  3. complete()

Whenever a new value is received from the observable, it is handled through the next() method. Whether an error reported by the observable is handled through the error() method. The complete() method comes into action when the observable has emitted all the data from the source and there are no more data to be received from the it.

Data received from the Observables are handled by the three methods of the Observer

Subscription

Now the obvious question is how does an observables know that the data should be sent to the observer to handle it? Here a subscriber comes into play. A subscriber is responsible to establish the connection between the Observer and the Observables. This is basically one method called the subscribe() method. We connect our observable to the observer which basically tells the observable that someone is listening to it to do something with the data the Observable emits.

Pic: Subscriber connects the Observable with the Observer

Example

export class Student {
    id: Number;
    name: String;
    roll: Number;
}

Lets say you have a model called Student. This model has property id, name and roll . This model is going to be the structure of a single entity of your data collection

import { Injectable } from '@angular/core';
import { Student } from './student.model';

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

students: Student[] = [{
    id: 1,
    name: 'John',
    roll: 001
},
{
    id: 2,
    name: 'Jack',
    roll: 003
},
{
    id: 3,
    name: 'Richard',
    roll: 003
},
];

  constructor() { }
}

Here’s where we create the collection of data. Note that we have to import the model to create a new collection of Student

import { Observable } from 'rxjs';

 public getStudentData(): any {
     const ObservableOfStudents = new Observable(observer => {
                observer.next(this.students);
     });

     return ObservableOfStudents;
 }

Now here is where we create our Observable. This is created in the StudentService. As you can see that we have also defined the Observer here. But, the observable won’t comes into action unless we define our Subscriber which essentially connects the Observable with the Observer.

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

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

    students: Student[] = [];

    constructor(private studentservice: StudentService) {}

    ngOnInit() {
       const ObservableOfStudents= this.studentservice.getStudents();
       ObservableOfStudents.subscribe(

       data => console.log('Observer receives the next value: '+data), 
       err => console.error('When receiving an error: ' + err), 
       () => console.log('Completed! no more data to receive') 
       );
    }
}

As we can see that the Subscription is defined here and it has three methods. The first method here is the next method which processes the value received. If the error is received the err method comes into action, whether the final method is the complete method which is executed when no more data is going to be emitted by the Observable in the future.

So, that was a pretty basic description of the key concepts and also the implementation of the Angular Observables. Hope this will help you in some way prior to implement and apply the concept in your project. Stay tuned. Thanks!

Leave a Reply

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