AppDividend
Latest Code Tutorials

How To Create Observables in Angular 9/8/7

1

Angular uses observables extensively in an event system and with the HTTP service. The Observable is not an Angular specific feature, but a new standard for managing async data. We can use Observables without Angular or with Angular. We can even create Observables in the Node.js platform or inside any Javascript library. RxJS is a famous library that provides Observables support. Let’s see what is Observables in Angular and how to create Observables in Angular.

What is Observables

The Observable is just a function, with minimal distinctive characteristics. Observables take in an “observer” (an object with “next”, “error” and “complete” methods on it), and return cancellation logic.

Observables are just lazy collections of multiple values over time. You can think of lazy observables as newsletters. For each subscriber, the new newsletter is created. The newsletters are then only sent to those people, and not to anyone else.

Now, if you keep that subscription open for the newsletter, you will get the new one every once in a while. In this example, the sender decides when you get new mail for the newsletter, but all you have to do is wait until it comes straight into your inbox.

An Observable sets up an Observer and connects it to a “thing” we want to get values from. That “thing” is called a producer and is a source of values, perhaps from the click or input event or something more complex such as communication over HTTP.

In Angular, we generally use an Observable when we got the data from the server. Async data is a perfect example of using Observables in Angular.

What is an observer in RxJS

When an Observable produces values, it then notifies the Observer, calling .next() when the new value was successfully captured and call the .error() method when an error occurs.

When we subscribe to the Observable, it will keep pushing any values to an observer until one of two things happens.

  1. When a producer says there are no more values to be pushed, in which case it will call the .complete() on the Observer. It notifies subscriber that there are no more values left.
  2. We (as the “consumers”) decide if we are no longer interested in those values or not, and we unsubscribe those observables.

When we want to compose those values returned from the Observable, before they reach our final .subscribe() block, the value is passed (or can be passed) through a chain of Observables, which is typically done via “operators”.

This chain is what we call an Observable sequence.

Each operator returns the new Observable to continue our sequence – also known as a “stream”.

Create Observables in Node.js platform

Observable.create() is an inbuilt RxJS method that creates new Observable. RxJS is a third-party library. So, we need to install using the following command.

npm install rxjs --save

The next step is to create an app.js file inside a root folder and write the following code.

// app.js

const { Observable } = require('rxjs');

const obs$ = Observable.create(function (observer) {
  observer.next('Observables on');
  observer.next('Node.js');
  observer.complete();
});

obs$.subscribe(val => console.log(val));

In the first step, we have required the Observable operator and then create a new Observable using create() method, which takes anonymous function.

Here, the Observer is an interface for a consumer of push-based notifications delivered by an Observable.

An object conforming to an Observer interface is usually given to the observable.subscribe(Observer) function, and the Observable will call the Observer’s next(value) method to provide notifications.

A well-behaved Observable will call an Observer’s complete() method exactly once or the Observer’s error(err) method exactly once, as the last notification delivered.

The Subscribe operator is a glue that connects an observer to the Observable. For an observer to see the items being emitted by the Observable, or to receive an error or completed notifications from the Observable, it must first subscribe to that Observable with this operator.

The standard implementation of the Subscribe operator may accept one to three methods (which then constitute the Observer), or it may take an object (sometimes called an Observer or Subscriber) that implements the interface.

Now, run the above file using the following command.

Output

➜  es git:(master) ✗ node app
Observables on
Node.js

Create Observables in Angular 9

Angular has inbuilt support for rxjs, and it automatically installed the rxjs library when installing a new Angular project.

We can import rxjs in any Angular component file using the following code.

import { Observable } from 'rxjs';

Okay, let’s write the following code inside the app.component.ts file.

// app.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  ngOnInit() {
    const simpleObservable$: Observable<string> = new Observable((observer) => {
      // observable execution
      observer.next('Welcome to');
      observer.next('Angular 9');
      observer.complete();
    });
    simpleObservable$.subscribe(val => console.log(val));
  }
}

Here, we have used the ngOnInit() lifecycle method. 

Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn’t do actual “work”.

So you should use constructor() to set up Dependency Injection and not much else.

In TypeScript, we can create a new Observable using the new keyword and takes the Observer as a parameter.

Then Observable created a producer that generates the values which can change over time.

To get the values from that Observable, we need to subscribe that observable using subscribe operator, and we finally get those values.

Our app.component.html file looks like below.

<div>
  <h2> How to create new Observables in Angular 9</h2>
</div>

Save the file and run the dev server using the following command.

ng serve -o

Please open the console panel of the browser to see the Observables values.

 

Observable in Angular 9

We can see in the console that we have created Observable successfully and subscribe to it to get the values.

So, this is how you need to create Observables in Angular and subscribe to it.

See also

Angular 9 Tutorial

Angular 9 Property Binding

Angular 9 Event Binding

1 Comment
  1. Amit Parmar says

    Thanks for the guide.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.