Angular Observable vs. Promise — How to Create & Use Them to Manage Data

Desislava Dincheva
Ignite UI
Published in
6 min readJun 15, 2022
Angular Promise vs Angular Observable

When it comes to Angular, there are two main types of data management: using Observables or Promises with both being capable of managing asynchronous code in JavaScript. At first glance, Observables are seen as a more advanced alternative to Promises. But, in fact, they are quite different. From having separate APIs, through having different motives, to offering distinct ways for handling the async model in JavaScript, Angular Observables and Angular Promises have their own powers.

How to know which one is right for your Angular project? Let’s discuss them in detail, compare each implementation, and see the functions, the advantages and disadvantages. On top of this, I will demonstrate how to use Angular Observables and Angular Promises with our low-code App Builder so you can handle asynchronous events easily and quickly.

Here is what the article will cover:

Try Ignite UI for Angular

What Is Promise in Angular?

Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API. Then, the controller (or the directive) takes on, registering up to three callbacks — success, error, and/or notifications.

There are four states of the Angular Promise:

  • fulfilled — action is fulfilled
  • rejected — action failed
  • pending — action hasn’t succeeded or failed yet
  • settled — action is either fulfilled or rejected

Something to remember is that Angular Promise is more passive compared to the Observable and cannot be canceled once it is started. In other words, when you pass the callback to the Promise constructor (controller or directive), it will either resolve or reject the function.

Now, there are several disadvantages when using Angular Promise.

  • Promises aren’t cancellable, and you have to wait until the callback returns an error or success.
  • Not suitable for centralized and predictable error handling as errors are sent to the child promise.
  • They don’t provide any operations.
  • Promises execute an async value only once.
  • Cannot be used for multiple values over time.
  • They become hard to manage with larger applications.
  • They cannot be retried.

How To Create Promises in Angular?

To create a promise in Angular, we just need to use the ‘new Promise(function)’ syntax. The promise constructor takes the function as a parameter, and that inner function takes resolve and rejects as a parameter.

Let’s see how this looks in the code snippet below.

creating Angular Promise

Now that we know how to create an Angular Promise, we will use it to implement a very simple scenario. The created Promise will help us validate whether the number is prime or not.

validating number with Angular Promise

And finally, to put our method in use, we will handle the Promise in the following way.

handling Angular Promise in Ignite UI for Angular

What Is Observable in Angular?

Observables provide more capabilities to you as they let developers run functions asynchronously and synchronously. They represent a stream of values that can handle 0, 1, or multiple events, using the same API for each. The thing that I personally like about Angular Observables is the number of operators simplifying coding, including: retry(), or replay(), map, forEach, reduce and more.

Just like Angular Promises, Observables in Angular also have their disadvantages.

  • Observables aren’t natively supported by browsers.
  • They require RxJS operators to get a new tailored stream of values.
  • Debugging the code with observables may be a bit more challenging.
  • You must have the know-how of extra tools and techniques to test the RxJS code.

How To Create Observables in Angular?

To create an Observable in Angular, first it is necessary to import Observable from rxjs, because as we learned above they are not natively supported.

Importing Angular Observable

To create a new Observable, we just need to use its constructor and add the logic that will be executed upon subscription. In our case, we will create an Observable that will return a great data source for our grid component.

Returning great data source with Angular Observable in Ignite UI

After that, what is left for us is to subscribe to the created Observable and bind the received data as a data source to our Grid component.

Binding data in Angular Observable

A great and more meaningful example of a use case for working with observables is using IgxGrid with Remote Data. As you can see in the example, only a small chunk of data is fetched initially when the component is rendered and on each scroll or data operation that is performed a new piece of the data is taken. This observable of type any[] is bound directly to the grid using async Angular pipe. The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.

Angular Promise and Angular Observable demo

Click here to see the sample and inspect the code right away.

How To Use Angular Observable and Promise in App Builder?

As we understand from the written above the most common scenario to use Observables is when we need to bind data to some component. To fetch data, we must make an HTTP request using HttpClient. The best way to do it is to carry it out into a separate service. All HttpClient methods return an RxJS Observable of something. In general, an Observable can return multiple values over time but an Observable from HttpClient always emits a single value and then completes, never to emit again.

In the App Builder, binding a component to a data source is easy and intuitive. You currently have the following options to choose from in order to use one of our predefined data sources:

  • Upload a JSON file or add a URL to a JSON file that contains your data.
  • Add/upload a Swagger definition file where all endpoints of your server are described and you can directly get your real data from there.

After that, no matter which approach you choose, you can use the Data drop down from our props panel to bind the data to the component — for example to the Angular grid.

Now we can look at the generated code in Angular. We give you a separate service where the data fetching is performed using the http get method.

And you can see in the MasterViewComponent ts file the subscription the data service performed. With this basis, you can conduct even more complicated scenarios whenever necessary.

Angular Observable vs Promise: What’s the Difference?

I decided to compose a table to present the differences between observables and promises in Angular. This way, you will be able to compare them in a more digestible and concise way.

Apparently, in the Angular Observable vs Promise comparison, Angular Observable wins. So, is there a good reason to use Promise, then? Absolutely.

Firstly, Observables come at a certain cost. As I mentioned before, they are not natively supported by browsers. Which means you must implement the RxJS library. And while it helps you create asynchronous or callback-based code, its bundle size can exceed 17.4kb.

Secondly, when your Angular app is asynchronous by default, there’s no better way to handle all asynchronous functions and events than using Angular Promise. Isn’t that right?

Next, if you don’t want to use reactive style or don’t care about streams of values and cancellable events, then go for Promises in Angular.

On a final note, we recently published an extremely detailed and helpful Angular UI Data Grid tutorial to help you learn how to create a full-featured Angular UI Grid from scratch. So, you might want to check it out as well. Click below.

Ignite UI for Angular

Originally published at https://www.infragistics.com on June 15, 2022.

--

--

Desislava Dincheva
Ignite UI

I am a Software dev at Infragistics for 5 years. My biggest motivation?The idea to streamline the way IT communities work with technologies to build innovations