+1 vote
in Angular by
What do you understand by observable and observer in Angular?

1 Answer

0 votes
by

Observable: An observable is a unique object just like a promise that that is used to manage async code. Observables are not part of the JavaScript language so the developers have to rely on a popular Observable library called RxJS. The observables are created using the new keyword.

See a simple example of observable to understand it better:

  1. import { Observable } from 'rxjs';  
  2. const observable = new Observable(observer => {  
  3.   setTimeout(() => {  
  4.     observer.next('This is a message from Observable!');  
  5.   }, 1000);  
  6. });   

Observer: Any object that has to be notified when the state of another object changes is called an observer. An observer is an interface for push-based notifications delivered by an Observable.

See the structure of an observer:

  1. interface Observer<T> {  
  2.   closed?: boolean;  
  3.   next: (value: T) => void;  
  4.   error: (err: any) => void;  
  5.   complete: () => void;  
  6. }   

The handler that implements the observer interface for receiving observable notifications is passed as a parameter for observable as follows:

  1. myObservable.subscribe(myObserver);  

Related questions

0 votes
0 votes
asked Jun 5, 2022 in Angular by Robindeniel
0 votes
asked Jul 12, 2023 in Angular by Robin
...