Latest Code Tutorials

Angular 7 Observables Tutorial With Example


Get real time updates directly on you device, subscribe now.

Angular 7 Observables Tutorial With Example is today’s leading topic. Observables provide the support for passing the messages between publishers(Creator of Observables) and subscribers(User of Observables) in your application. Observables are declarative that is, you define the function for publishing values, but it is not executed until the consumer subscribes to it. The observable can deliver the multiple values of any type like literals, messages, or events, depending on the context. As a publisher, you can create an Observable instance that defines a subscriber function. This is a function that is executed when the consumer calls the subscribe() method.

Define Angular Observables

The handler for receiving the observable notifications implements the Observer interface. It is an object that defines the callback methods to handle the three types of notifications that an observable can send. These are the following.

  1. next: Required. The handler for each delivered value called zero or more times after execution starts.
  2. error: Optional. The handler for error notification. An error halts execution of the observable instance.
  3. complete: Optional. The handler for the execution-complete notification. Delayed values can continue to be delivered to the next handler after execution is complete.

Subscribing Angular Observables

An important note here is that the Observables instance begins publishing the values only when someone subscribes to it. You can subscribe the observables by calling the subscribe() method of the instance and passing an observer object to receive the notifications.

  x => console.log('Observer got a next value: ' + x),
  err => console.error('Observer got an error: ' + err),
  () => console.log('Observer got a complete notification')

Creating Angular Observables

Use the Observables constructor to create an observable stream of any type. We will develop a Stream of type Array in our example. The constructor takes as its argument the subscriber function to run when the observable’s subscribe()  method executes. The subscriber function receives an Observer object and can publish the values to the observer’s next() method.

You can create a new observable like this.

const obs = new Observable();

You will learn how we can use Observables in Real life by below Angular Observables Example.

Angular 7 Observables Tutorial With Example

We start Angular Observables by learning an example. So let us install Angular 7 Project using Angular CLI.

Step 1: Create an Angular 7 Project

Type the following command to create Angular Project using Angular CLI.

ng new observe


Angular 7 Observables Tutorial With Example

Now, go inside the project and open the project in VSCode or any other editor.

cd observe && code .

Also, install the Bootstrap CSS Framework.

npm install bootstrap --save

Step 2: Create a service and model files

Create an Angular service using the following command.

ng g s student --spec=false

It will create a file student.service.ts file inside the src >> app folder.

We have created service because we will use service to handle the data that needs to be displayed on the frontend.

Also, create a new file inside the src >> app folder called student.model.ts and add the following code inside it.

// student.model.ts

export class Student {
    id: Number;
    name: String;
    EnrollmentNumber: Number;
    College: String;
    University: String;

That means we have defined the Student type in our application which has the id, name, enrollment number, college, and university properties.

Now, we need to add the demo data inside the student.service.ts file. The data is the type of Student model which we have defined above.

// student.service.ts

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

  providedIn: 'root'
export class StudentService {

students: Student[] = [{
    id: 1,
    name: 'Krunal',
    enrollmentnumber: 110470116021,
    college: 'VVP Engineering College',
    university: 'GTU'
    id: 2,
    name: 'Rushabh',
    enrollmentnumber: 110470116023,
    college: 'VVP Engineering College',
    university: 'GTU'
    id: 3,
    name: 'Ankit',
    enrollmentnumber: 110470116022,
    college: 'VVP Engineering College',
    university: 'GTU'

  constructor() { }

Step 3: Create an Observable

Now, we have defined the private data. We need to create one function inside the service that will return that data in the form of observable. So we can subscribe to it, and we get the data and display it on the frontend. Add the following code inside the student.service.ts. Put the getStudents() function inside the class after the constructor.

Related Posts
1 of 17
// student.service.ts

import { Observable } from 'rxjs';

 public getStudents(): any {
     const studentsObservable = new Observable(observer => {
            setTimeout(() => {
            }, 1000);

     return studentsObservable;

So, here we have done is first import the Observable from rxjs. Then defined one function that will return an observable. The observable object gets one argument that has a timeout function. So after 1 second, it will produce the whole student’s array if the subscriber subscribes the observable.

In simple terms, here studentObservable are publishing our primary data array that is students. So if any entity needs to get the values out of observable, then it first needs to subscribe that observable and then studentObservable starts to publish the values, and then subscriber get the values.

Step 4: Define the Subscriber

We have created the Publisher for the Observables. Now, we need to create a subscriber. So write the following code inside the app.component.ts file.

// app.component.ts

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

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

    students: Student[] = [];

    constructor(private studentservice: StudentService) {}

    ngOnInit() {
        const studentsObservable = this.studentservice.getStudents();
        studentsObservable.subscribe((studentsData: Student[]) => {
            this.students = studentsData;

Here, we have subscribed the observable and get the students data.

The final step is to display the data.

Step 5: Display the data

Add the following code inside the app.component.html file.

<!-- app.component.html>

<div class="container">
    <div class="row" style="margin-top: 30px">
        <div class="col-md-3 col-xs-6" *ngFor="let student of students">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">{{ }}</h5>
                    <h6 class="card-subtitle">{{ student.enrollmentnumber }}</h6>
                    <p class="card-text">{{ }}</p>
                    <p class="card-text">{{ }}</p>
                    <a class="btn btn-primary" href="#" >Go somewhere</a>

Save the file and start the angular development server.

ng serve

Go to the http://localhost:4200 and see the result after 1 second.


angular observables

So, we have successfully get the data using Observables.

Remember, Observables producing the values Asynchronously. Observables are the lazy collections of multiple values or streams over time. It is like a subscription to the newsletter, if you keep that subscription open, you will get the new one every once and a while. The sender decides when you get it, but all you have to do is to wait until it comes straight into your inbox.

The critical thing here is to understand when using observables is that observables push. Push and pull are two different ways that describe how the data producer communicates with the data consumer.

Simple Code of Observables

import { Observable } from "rxjs/Observable"

// create observable
const simpleObservable = new Observable((observer) => {
    // observable execution"hello")

// subscribe to the observable

// dispose the observable

Error handling

The Observables produce values asynchronously that is why try/catch block will not effectively work here to catch the errors. So In the sense of Observables, you can handle the errors by specifying an error callback on the observer. 

Producing an error also causes the observable to clean up subscriptions and stop producing values. An observable can either produce the values (calling the next callback), or it can complete, calling either the complete or error callback.

  next(num) { console.log('Next num: ' + num)},
  error(err) { console.log('Received an errror: ' + err)}

Disposing observables

When you subscribe to the Observable, you get back the subscription, which represents an ongoing execution. Just call unsubscribe() to cancel the execution. So you are free to that Observable.

  1. Kay says

    You need to cover observer pattern at a high level, subscriber models, multiple susbcription, caching scenarios, cold v hot, connectable observables, operators etc. In the cases you’ve outlined, manual unsubscription shouldn’t be needed and should be discouraged as correctly written finite observables should handle subscriber unsubscription internally and complete the observable. Hence why you don’t need to unubscribe from HttpClient observables.

    Side note: From a purely angular 7 standpoint this entire post defies best practice. Was the angular 7 ref just for the SEO potential?

  2. HEMANG says

    Isn’t this just Rxjs? What is Angular 7 has to do with Observables?
    By reading the title, I thought Observables are now part of Angular version 7.

    1. Krunal says

      Yes, you are right, both are a totally different thing. The main motto of this example is that how we can use Angular with Observables and yes if you install angular then rxjs will be installed as well. So rxjs is kind of part of angular projects.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.