Site icon

Angular Observables Tutorial

Angular Observables

Angular Observables

Angular Observables provide support for passing messages between publishers and subscribers in your application.

Observables offer significant benefits over other techniques for event handling, asynchronous programming, and handling multiple values.

Observables are declarative—that is, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.

In a real-world example, we can say that the Internet service offered by mobile devices is an observable. It is available only to the people who have subscribed to it. We continuously receive this service from the service provider only as long as this service is on and we are subscribed to it.

Creating a Basic Observable

Let’s create a basic observable first and then see what they offer us.

Check out the code below for an example:


import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs/Observable'
@Component({
  selector: 'app-observable-demo',
  templateUrl: './observable-demo.component.html',
  styleUrls: ['./observable-demo.component.css']
})
export class ObservableDemoComponent implements OnInit
 {
  private data: Observable;
  private fruits: Array = [];
  private anyErrors: boolean;
  private finished: boolean;
  constructor() { }
ngOnInit(){
}
Start(){
  this.data = new Observable
  (
    observer =>
    {
            setTimeout(() =>
            {
                observer.next('Apple');
            }, 1000);
           
            setTimeout(() =>
            {
                observer.next('mango');
            }, 2000);
            setTimeout(() =>
            {
                observer.next('Orannge');
            }, 3000);
            setTimeout(() =>
            {
                observer.complete();
            }, 4000);
           
   }
);
let subscription = this.data. subscribe(
fruit => this.fruits.push(fruit),
    error => this.anyErrors = false,
    () => this.finished = true
);
this.; }}

Let’s go through this code, step-by-step:

1. Import the observable from rxjs/Observable and include it in the component.

2. Next, create the observable object, which, in our example, we are creating the observable object which will be a string.

3. Next, subscribe to the Observable in the application which will allow us to listen to the data that is coming along with it.

4. With the subscription, we used three callbacks which already accept the data emitted by the observable. The second callback given is the Error call.

To Invoke this observable, we need to make some changes in the template that we are using. The code I used for the template looks like this:

<p >Observable Basics</p>
<hr/>
<b>Observable Data </b>
<div *ngFor="let f of fruits"> {{ f | uppercase }}</div>
<hr>
<div * >
<b>Error Status :</b>
 {{anyErrors=? 'error occured ' : 'It All Good'}}
<hr>
</div>
<div > <b> completion status : </b> {{ finished= ? 'Observer completed ': '' }}</div>
<hr>
<button (click)="start()">Start Emitting</button>

 

Read About: Regular Expressions – (Regex) – Regular Expression

The above code displays the fruit names that we are emitting in the application. The output of the code can be seen below:

 

Exit mobile version