Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Observables With Angular 5

DZone's Guide to

Observables With Angular 5

A web developer gives us a tutorial on how to use observables in our TypeScript code, what this does for our application, and the different types of observables.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

We have a case where we use observables to populate the UI from the external data asynchronously. Angular uses the same thing for this task, so let’s see how we can use the observables and use them in an Angular application.

What Are Observables?

Observables are a lazy collection of multiple values, or data, over a period of time. Observables open the continuous channel of communication where multiple values are emitted over time. This allows us to determine the pattern of the data.

In a real-world example, we can say that the Internet service offered by mobile devices is an observable. It is available only to the people who have subscribed to it. We continuously receive this service from the service provider only as long as this service is on and we are subscribed to it.

Creating a Basic Observable

Let’s create a basic observable first and then see what they offer us.

Check out the code below for an example: 

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;

  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.; }}

Let’s go through this code, step-by-step:

1. Import the observable from rxjs/Observable and include it in the component.

2. Next, create the observable object, which, in our example, we are creating the observable object which will be a string.

3. Next, subscribe to the Observable in the application which will allow us to listen to the data that is coming along with it.

4. With the subscription, we used three callbacks which already accept the data emitted by the observable. The second callback given is the Error call.

To Invoke this observable, we need to make some changes in the template that we are using. The code I used for the template looks like this:

<p >Observable Basics</p>
<hr/>
<b>Observable Data </b>
 <div *ngFor="let f of fruits"> {{ f | uppercase }}</div>
 <hr>
<div * >
  <b>Error Status :</b>
 {{anyErrors=? 'error occured ' : 'It All Good'}}
  <hr>
</div>
<div > <b> completion status : </b> {{ finished= ? 'Observer completed ': '' }}</div>
<hr>
<button (click)="start()">Start Emitting</button>

The above code displays the fruit names that we are emitting in the application. The output of the code can be seen below:

Observable 1

Next, want to see how we can handle errors in our observers.

Error Handling in Observables

There might be a case where an error is generated when we are using observables. If something unexpected occurs, we can use the observable error function in our subscription to check what went wrong.

Let’s check the component code for any errors: 

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;



  ;



  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.error(new Error('error occured'));

            }, 4000);

            setTimeout(() =>

            {

                observer.complete();

            }, 5000); });

let subscription = this.data.

subscribe(

    fruit => this.fruits.push(fruit),

    error => this.anyErrors = true,

    () => this.finished = true

);

this.; }}

We can see the output below:

Observable2

Something to consider in this case is that we cannot see the completion status when the Emit event is finished.

Why is that? Because the complete event won’t be fired if it is added after the error in the code, so we should always have some function which will stop all the component from running in the application if an error is detected.

Using Observables for Form Events

Let’s see how we can use observables in Angular forms.

The components that we will be using will look like what I've got below>

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

import {Observable} from 'rxjs/Observable'

import {FormControl, FormGroup, FormBuilder} from '@angular/forms';

import 'rxjs/add/operator/map';



@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;

  mathform: FormGroup;

  inputnumber :FormControl

  squaredata:number;

  ;



  constructor(private fb: FormBuilder) {

 

this. FormControl();



    this.mathform = fb.group({

        inputnumber:this.inputnumber

    })

this.inputnumber.valueChanges.map(n=>n*n)

    .subscribe(power=>this.);

  };

Here, we have used the Reactive form. In this code, whenever we use the reactive forms, every field is considered to be an observable. Thus, we can subscribe to that field and listen to any changes made to that input value.

In the above code, we have created a form by using the FormControl and added to the FormGroup. In this control, we have the property  valueChanges, which always returns the observable. Now, whenever I type the number in the field, I get the square of that number.

The template code for the above change will look like what I've got below.

<form [formGroup]="mathform">
  <input formControlName="inputnumber">
</form>

<hr>

<div>
  Square of the number is :: <b>{{squaredata}}</b>
</div>

The output for this code is below:

Observable22

Unsubscribing the Observable

There is a good chance that we will eventually need to unsubscribe from the observable and do some cleanup, like resource release. Angular comes with Unsubscribe() which will unhook the members listening to the Observable stream. Also, there is a way to provide the custom call back method, OnUnsubscribe(), which will be called to manually clean up the things after the subscription has ended.

Do we need to call unsubscribe every time we call observables? The answer is no, observables have the built-in ability to dispose of all their resources whenever the Complete or error method gets called in the application.

Hot and Cold Observables

Generally, there are two types of the observables. The first one is Cold observables and the one is Hot observables.

What Are Cold Observables?

Cold observables are the ones that are explicitly invoked by the producer. In our first example, where we used the set timeout method we were manually creating and subscribing the observable inside the start functions. This is an example of a cold observable.

What Are Hot Observables?

An example of a hot observable would be when we are getting the power of a number which has been invoked, and, as soon as the value change occurs, it will start the subscribing to the stream before waiting for the producer to send the signal to subscribe.

Conclusion

So, this was all about the observables. In the next article, we will see how we can use observables with HttpClient for calling HTTP methods and how we can transform the result and discover errors.

GitHub link to the source code.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
angular 5 ,observable

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}