Categories
Angular HTML Javascript

Angular and Observables: how to avoid the subscription with the help of Async Pipe

If you have been using Angular for a while, probably you have met and used the Observables. Observables are part of a paradigm called Reactive Programming, and are included in Angular with the rxjs library. As you can read on the links, Reactive programming and Observables help you work with asynchronous data streams.

You can read more info about Observables in this excellent article

As you can see there, in order to be able to use the Observables, you have to subscribe to them. Subscribing is like calling a function, or invoking the Observable, then you can see the results produced by the Observables.

But when you are using an Observable and want to show the data emitted by the Observable on your component´s template, you can avoid the subscription and, thus, a good amount of logic and code. That is possible with the Async pipe.

It unwraps a value from an asynchronous primitive so you can apply it on the observable and get its result without any subscription.

Let´s see it with a simple example

We have a regular angular component where we have defined an array of numbers and an Observable. The only thing we will do is, create an Observable from that array, and then we will use the Async pipe in the component´s template to show the results.

To create the observable we will use rxjs operators. In this case we will use the of( ) operator

With an array, the of( ) operator emits the whole array at once as an observable, then we can iterate over it and apply the Async pipe.

RELATED POSTS  No more free Heroku? How to move your Node backend to Render.com

For more info about this operator and the difference with another commonly used operator to generate observables ( from( ) ), please check following links:

Enough talking, we will see the code:

 

observables-test.component.ts

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

import { Observable, of } from 'rxjs';

@Component({

  selector: 'app-observables-test',

  templateUrl: './observables-test.component.html',

  styleUrls: ['./observables-test.component.css']

})

export class ObservablesTestComponent implements OnInit {

  
 //Observable should have same type as the array, in this case, number[]
  public observableWithAsync$:Observable<number[]>;


  //this array will be passed to the observable using the of() operator

  public arrayToBePassed:number[];


  constructor() {

    this.observableWithAsync$=new Observable();

    this.arrayToBePassed=[0,1,2,3];

   }

  ngOnInit(): void {

    this.observableWithAsync$=of(this.arrayToBePassed);  


  }

}

If you want to know about the differences between the constructor and the ngOnInit, please read this useful link.

Summarizing:

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. ngOnInit() is a better place to “start” – it’s where/when components’ bindings are resolved.

 

Also you could note, I created the Observables using a $ at the end. That has a reason:

https://stackoverflow.com/questions/37671700/angular2-style-guide-property-with-dollar-sign

OK, once we have created the Observable, all we have to do to use it on our template is this:

observables-test.component.html

<ul>

    <li *ngFor="let number of observableWithAsync$ | async">

        {{number}}

    </li>

</ul>

Now, we see all we have to do is iterating over the observable and apply the Async pipe. Output on the screen will be:

RELATED POSTS  How to use and customize Angular Material snackbars

This way we will avoid subscriptions and will certainly simplify our code.

Image provided by Luisella Planeta Leoni LOVE PEACE 💛💙 en Pixabay