This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

Angular Observable


An observable is a sequence of items that arrives asynchronously over time. This tutorials explains the concepts of observables in Angular and how they are used in Angular applications.  When we discuss about Angular Observable we keep following things in mind Reactive programming, data streams, Observable, Observers, RxJS etc. So it is very important to understand in brief these things before using observables in angular.

Example

Here is a real-world example from that we can understand concept of observables in better way. You may think about newspaper where subscribers receive newspaper while non-subscribers do not. The below image show observable concept.

Angular Observable Example

In the above image,

  1. Source - Sequence of information(Day News information )
  2. Newspaper Company - Convert that information in news paper information such as heading, body etc.
  3. Subscriber - Those houses which recieve the newspaper subscribe to the commany.

In the above scenario:

  1. The Sequence of information or source is the Observable stream.
  2. The person or house recieve news paper is the Observer.
  3. The act of which house subscribe for news paper with company is known as subscribing.
  4. The act of not recieveing newspaper is called unsubscribing;

What is RxJS?

RxJS stands for Reactive Extensions for JavaScript. It is a library that makes it possible for us to work with these streams of data. In RxJS, the Observer is an Object with 3 built-in methods. The Houses are the Observer and the newspaper that's streaming is the Observable. Being the Observer, you can get three different notifications: next, error, and complete.

  1.  Next - Whenever the next House comes through the data stream, you get the next notification.
  2. Error - If there is any proble to recieve newspaper. you'll get an error notification.
  3. Complete - Once the newspaper recieved is complete, you get the complete notification.

Import the Observable from the rxjs library.

import { Observable } from 'rxjs';

There are few points which are useful to understand promise in better way.

1. Observable emits multiple value at a time

The below example show that firstly we have create object of  Observable and define the values First, Second and Third.

   //  Observable Emits multiple values       
        const multipleValueObservables = new Observable((observer) => {
          observer.next('First');
          observer.next('Second');          
          observer.next('Third');
        });           
        multipleValueObservables.subscribe((value) => console.log("multiple values :" + value));

The above example will produce multiple value at a time.

Angular Observable multiple value

2. Observable executes only when someone is subscribing

It will execute when it is called or subscribing to that observable. The below example defines how to subscriber.

// Observable - Executes only when it is called or someone is subscribing      
    const observable = new Observable(() =>
      console.log(`Observable is called`)
    );
    observable.subscribe();

The above example will produce following output.

Angular Observable Subscriber

3. Observable can be cancellable  

It can be cancellable when we unsubscriber it.

//Observable - Can be cancellable    
const cancellableObservables = new Observable((observer) => {
  setInterval(() => {
    observer.next('First');
  observer.next('Second');          
  observer.next('Third');
  }, 1000);    
});               
const cancellableSubscription = cancellableObservables.subscribe((value) => console.log("multiple values :" + value));
cancellableSubscription.unsubscribe();

The above code will not produce any output.

4. Observable possibly asynchronous

//Observable possibly asynchronous
      const possibleAsyncObservable = new Observable((observer) =>
      observer.next(5)
    );
    possibleAsyncObservable.subscribe((value) =>
      console.log("Possible Async observable:" + value)
    );

Angular asynchronous

6. Handling an HTTP request with an Observable in Angular

Let's now see how to use Observable in Angular to work with HTTP asynchronously. we will learn that with a example.

import { Component } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ObservableApp';
  constructor(private httpClient: HttpClient) {    
  }
   ngOnInit() {

this.getemployee().subscribe(res => {(res as []).forEach((data: any) => {
  console.log(JSON.stringify(data));  
    })
  }
);  
}
 
  getemployee() {
    return this.httpClient.get('https://localhost:44340/api/employee');
  } 
}     
      

Add the following code in 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, HttpClient } from "@angular/common/http";

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

Now run the applicatyion and check browser console.

Angular observable with http or service

Now run the over all code to understand Observable better way.

import { Component } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ObservableApp';
  constructor(private httpClient: HttpClient) {    
  }
   ngOnInit() {
      
//Observable - Can be cancellable    
const cancellableObservables = new Observable((observer) => {
  setInterval(() => {
    observer.next('First');
  observer.next('Second');          
  observer.next('Third');
  }, 1000);    
});     


 // Observable - Executes only when it is called or someone is subscribing       
 const observable = new Observable(() =>
 console.log("Observable is called")
);
observable.subscribe();          
   //  Observable Emits multiple values       
   const multipleValueObservables = new Observable((observer) => {
     observer.next('First');
     observer.next('Second');          
     observer.next('Third');
   });           
   multipleValueObservables.subscribe((value) => console.log("multiple values :" + value));

   //Observable possibly asynchronous
const possibleAsyncObservable = new Observable((observer) =>
observer.next(5)
);
possibleAsyncObservable.subscribe((value) =>
console.log("Possible Async observable:" + value)
);

const cancellableSubscription = cancellableObservables.subscribe((value) => console.log("multiple values :" + value));
cancellableSubscription.unsubscribe();  

this.getemployee().subscribe(res => {(res as []).forEach((data: any) => {
  console.log(JSON.stringify(data));  
    })
  }
);  
}
  getemployee() {
    return this.httpClient.get('https://localhost:44340/api/employee');
  } 
}    

Output

Angular observable output


Prev Next