Angular Promises Versus Observables

Angular Promises Versus Observables

In this blog, we are going to see what observables are and how they are superior to promises with the help of Syncfusion’s Angular Charts component. Both observables and promises help us work with asynchronous functionality in JavaScript. Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time.

Angular Promises vs. Observables

Let’s see the difference between observable and promise (observable vs promise).

ObservablesPromises
Emit multiple values over a period of time.Emit a single value at a time.
Are lazy: they’re not executed until we subscribe to them using the subscribe() method.Are not lazy: execute immediately after creation.
Have subscriptions that are cancellable using the unsubscribe() method, which stops the listener from receiving further values.Are not cancellable.
Provide the map for forEach, filter, reduce, retry, and retryWhen operators.Don’t provide any operations.
Deliver errors to the subscribers.Push errors to the child promises.

Now let’s see code snippets/examples of a few operations defined by observables and promises.

OperationsObservablesPromises
Creationconst obs = new Observable((observer) => { observer.next(10); }) ;const promise = new Promise(() => { resolve(10); });
TransformObs.pipe(map(value) => value * 2);promise.then((value) => value * 2);
Subscribeconst sub = obs.subscribe((value) => { console.log(value) });promise.then((value) => { console.log(value) });
Unsubscribesub.unsubscribe();Can’t unsubscribe

With this information, we have some idea about what observables and promises are, how they’re initialized, etc. Now let’s see the practical usage of them with the help of the Syncfusion Charts component. If you’re looking for stunning charts for your Angular application, you can check out the Syncfusion’s Angular Charts component, which provides you with a variety of impressive features. To get started with the Syncfusion Charts component, please see the blog How to Create Beautiful Charts in Angular.

Let’s see how to load data to the Syncfusion Charts component with the help of promises and observables. First, I am going to use a promise to load the initial data to a chart and then an observable to update it with dynamic data.

Populating the chart with data using promises

First, I am going to populate the chart with some data from services. For that, initialize the chart with a series and create a service for the data.

` <e-series-collection>
      <e-series> </e-series>
  </e-series-collection>`

export class AppComponent  {

  public chartData: Data[];
  constructor(private dataService: DataService) { 

  }

}

Now get the data from dataService with the help of a promise and assign it to the chart dataSource.

` <e-series-collection>
      <e-series [dataSource]='chartData' type='Spline' xName='year' yName='sales'> </e-series>
  </e-series-collection>`

export class AppComponent  {

  public chartData: Data[];
  constructor(private dataService: DataService) { 

  }
  new Promise((resolve, reject) => 
                   {
                    resolve(this.dataService.getData())
                   }
              ).then((value : Data[]) => 
                    this.chartData = value
              ).catch((err) => 
                     this.chartData = null
              );   
}

Data emitted by the promise is visualized in a Syncfusion chart in the following screenshot.

Data emitted by the promise is visualized - Promise in Angular

Dynamically updating chart data using observables

With this, a chart was rendered with some initial data. Let’s assume that the service is updating its data every 1000ms. Then, we must get the data from the service every 1000ms and assign it to the chart using observables.

 this.Obs = new Observable((observer) => {
              observer.next(this.dataService.getData(true));
              setInterval(() => {
                observer.next(this.dataService.getData(false));
               }, 1000)
 });

Now, you can see the chart is being updated with the live data from the service.

Updating live data on the chart using observables

Conclusion

In this blog, we learned about the difference between promise and observable (promise vs observable) in Angular with the help of the Syncfusion Charts component. Check out the example for promise vs observablehere. To learn more about the Syncfusion Charts component for Angular, take a look at the documentation to explore all its features and API.

The Syncfusion Angular UI Components library is the only suite that you will ever need to build an application, since it contains over 65 high-performance, lightweight, modular, and responsive UI components in a single package. Download our free trial from our website. You can also explore our online angular demos.

If you have any questions about these controls, please let us know in the comments below. You can also contact us through our support forum, support portal, or feedback portal. We are happy to assist you!