Categories
Share on twitter
Share on facebook
Share on linkedin

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 the Syncfusion Charts control. 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. Let’s see the difference between these two.

Observables Promises
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 of a few operations defined by observables and promises.

Operations Observables Promises
Creation
const obs = new Observable((observer) => {

observer.next(10);

}) ;
const promise = new Promise(() => {

resolve(10);

});
Transform
Obs.pipe(map(value) => value * 2);
promise.then((value) => value * 2);
Subscribe
const sub = obs.subscribe((value) => {

console.log(value)

});
promise.then((value) => {

console.log(value)

});
Unsubscribe
sub.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 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 in a Syncfusion chart.
Data emitted by the promise is visualized in a Syncfusion chart.

Dynamic update using an observable

As you can see in the previous code, the promises emit a single value for our request. Suppose the service keeps updating its data; then we will have multiple values over the period of time. An observable helps us to get the values.

Create an observable and subscribe it to get the values.

 this.Obs = new Observable((observer) => {
            observer.next(this.dataService.getData(true));
          });
 this.Obs.subscribe((value) => {
      this.chartData = value;
 }

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.

 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.

Data emitted by the promise is visualized in a Syncfusion chart with live update.
Data emitted by the promise is visualized in a Syncfusion chart with live update.

Conclusion

In this blog, we learned about the difference between observables and promises in Angular with the help of the Syncfusion Charts component. Check out the sample here. 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 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 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 forumDirect-Trac, or feedback portal. We are happy to assist you!

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin

Leave a comment

Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top