Friday, March 16, 2018

Observable in Angular

Observables are a lazy collection of values. Observables open the continuos channel of communication where multiple
values are emitted over time.

Example : Internet service on mobile is an example of observable it is available for those who have subscribed it.

Observable.Component.ts

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<string>;  
  private fruits: Array<string> = [];  
  private anyErrors: boolean;  
  private finished: boolean;  
  
  processed=false;  
  
  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.processed=true; }} 

Observable.Component.html

<p style="padding-left:300px;font-weight:bold;font-size: 50px">Observable Basics</p>  
<hr/>  
<b>Observable Data </b>  
 <div style="border: 3px;padding-left:150px;text-align: " *ngFor="let f of fruits"> {{ f | uppercase }}</div>  
 <hr>  
<div *ngIf='anyErrors' style="border: 3px;padding-left:0px" >  
  <b>Error Status :</b>   
 {{anyErrors==true? 'error occured ' : 'It All Good'}}   
  <hr>  
</div>  
<div style="border: 3px;padding-left:0px"> <b> completion status : </b> {{ finished==true ? 'Observer completed ': '' }}</div>  
<hr>  
<button style="margin-top: 2rem;" (click)="start()">Start Emitting</button>  

Source : https://www.c-sharpcorner.com/article/observables-with-the-angular-5/

No comments:

Followers

Link