Monday, October 11, 2021

Custom Observable in Angular

 How to Create a Custom Observable in Angular

Angular makes use of observables as an interface to handle a variety of common asynchronous operations.

Steps to create custom observable in Angular

1. First thing is to create instance of observable with the help on Observable.create() method
2. An observable can send three types of notifications-
    
    nextWith the next value, observer sends a value that can be a number, a string or an object.
    
    error - Notify error in observable

    completeNotify the execution of observable completed

3. Subscribe an observable instance using subcribe() method
4. Unsubscribe observable using unsubscribe() in onDestroy


export class HomeComponent implements OnInit, OnDestroy {
  private onSubcription!: Subscription;
 
  constructor() { }
 
ngOnDestroy(): void {
    this.onSubcription.unsubscribe();
  }

  ngOnInit(): void {
     const customObservable = Observable.create((observer: Observer<Number>) => {
       setInterval(
         () => {
           let data = Math.floor(Math.random() * 10);
           observer.next(data);
           if (data == 6)
             observer.error("invalid number");
           else if (data == 8)
             observer.complete();
         }, 1000);
     });

     this.onSubcription = customObservable.subscribe((count: Number) => {
       console.log(count);
     },(error: string) =>
     {
      console.log(error);
     },() =>{
       console.log("completed");
     })
  }
}





1 comment: