Angular Observables

Posted By : Vaibhav Baliyan | 30-Jul-2020

Angular Observables

Observables aid in passing data between different parts of the application. Frequently used in Angular, observables are a recommended technique for event handling, asynchronous programming, and handling multiple values.

Observables are declarative i.e you define a function for publishing values, but it is not executed until someone subscribes to it. The subscriber then receives notifications until the function completes, or until the person unsubscribes. An observable can deliver multiple values like literals, messages, or events, depending on the context. The API for receiving values is the same whether the values are received synchronously or asynchronously. Observables are used in Angular and are recommended for application development as well.

 

Defining Observers

The handler for receiving observable notifications implements the Observer interface. It's an object which defines the callback method to handle three types of notifications that an observable can send:

          - next (required)

          -error (optional)

          -complete (optional)

The object of an observer can define any combination of these handlers.

 

Subscribing to Observables

The instance of an observable begins publishing values only when someone subscribes to it. Subscribe to it by the use of subscribe() method of the instance, passing an observer object to receive notifications.

example: 

         const Observable = of(1, 2, 3);

          const Observer = { next: a => console.log(a),

          error: test => console.error(test),

          complete: (void) => console.log('Observer got a complete notification'),

          };

          Observable.subscribe(Observer);

 

The subscribe method can accept callback function definitions inline, next, error, and complete handlers.

 

Observables creation

Use the observable constructor to create an observable stream of any type. The constructor takes as its argument the subscriber function to run when the observable subscribe() method executes. A subscriber function receives an object and can publish values to the observer next() method.

example:  The subscriber function is defined inline in this example.

         function Demo(target, name) {

          return new Observable((observer) => {

          const handler = (e) => observer.next(e);

          target.addEventListener(name, handler);

          return () => {

          target.removeEventListener(name, handler); }; }); }

 

Are you planning to boost the speed of your current app? Oodles ERP is the Angular Development Company you need! Our  Angular app developers create mobile apps that seamlessly improve app speed and performance. Get in touch with our experts for more details!

 

 

 

 


Please remove URL from text

Comment is required

Sending message..
Connect with us