Promises and Observables in Angular

In this tutorial we will learn how to use Promises and Observables in Angular. Both Promises and Observables will help us work with the asynchronous functionalities in JavaScript. They are very similar in many cases, however, there are still some differences between the two as well, promises are values that will resolve in asynchronous ways like HTTP calls. On the other hand, observables deal with a sequence of asynchronous events.

Promise in Angular

  • Helps you run functions asynchronously, and use their return values (or exceptions), but only once when executed.
  • Usually only use with async data return
  • Having one pipeline
  • Cannot be retried (Promises should have access to the original function that returned the promise to have a retry capability)
  • Not lazy
  • Calls the services without .then and .catch
  • Does not provide any operators

Promise Example in Angular:

function doAsyncTask() {
  var promise = new Promise((resolve, reject) => {
    this.http.get(`${default_api_url}/api`).subscribe((data)=>{
        resolve(data);
      }, (e) => {
        reject(e);
      })
  });
  return promise;
}

doAsyncTask().then(
  () => console.log("Task Complete!"),
  () => console.log("Task Errored!"),
).catch((err) => console.error(err));

Observable in Angular

  • Helps you run functions asynchronously, and use their return values in a continuous sequence (multiple times) when executed.
  • By default, it is lazy as it emits values when time progresses.
  • Are cancellable
  • Are re-triable by nature such as retry and retry When stream data in multiple pipelines
  • Having array-like operations like map, filter etc
  • Can be created from other sources like events
  • Provides the map, forEach, filter, reduce, retry, and retryWhen operators
  • Is not called until we subscribe to the Observable

Observable Example in Angular:

import {Observable} from 'rxjs';

obs;

export class ExampleComponent implements OnInit {
  
  constructor() { 
    this.obs = new Observable((observer) => {
      console.log("Observable starts")
      observer.next("1")
      observer.next("2")
      observer.next("3")
      observer.next("4")
      observer.next("5")

      observer.error("5")
      //observer.complete("5")
    }).pipe(
    filter(data => data > 2),   //filter Operator
    map((val) => {return val as number * 2}), //map operator
    )
  }
  
  ngOnInit() {
    this.obs.subscribe(
      val=> { console.log(val) },
      error => { console.log("error")},
      () => {console.log("Completed")}
      )
  }

  ngOnDestroy() {
    this.obs.unsubscribe();
  }

}

So, we can use the Promises and Observables in Angular for our async actions in different ways. Here is also an official docs.

Recommended

How to Create Multiple Parameters Dynamic Routes in Laravel

Laravel 8 Multiple Database and Resource Routes with Controllers

Optimize Database Queries in Laravel

Flash Messages in AngularJS

Create REST API in Node.js

Create Filters in AngularJS

For more Angular Tutorials

If you like this, share this.

Follow us on FacebookTwitterTumblrLinkedInYouTube