Promise vs Observable in Angular

Knoldus Blog Audio
Reading Time: 2 minutes

In Angular, we can use either Promise or Observable for handling asynchronous data. Both get and post method of Http and HttpClient return Observable and it can be converted into Promise using toPromise() method. So, what’s the difference when they both are dealing with asynchronous data.

What actually the difference is?

Promise emits a single value while Observable emits multiple values. So, while handling an HTTP request, Promise can manage a single response for the same request, but what if there are multiple responses to the same request, then we have to use Observable. Yes, Observable can handle multiple responses for the same request.
Let’s implement this with an example.

Promise

Output

Explore how to use Resolve -Promises in Angular 2. Resolve is a powerful technique to achieve the best user experience when browsing between pages in your app. It also makes the component’s code much cleaner in contrast to fetching data inside the component.

 Observable

Output

So, in the above code snippet, I have created promise and observable of Promise and Observable type respectively. But, promise returns the very first value and ignore the remaining values whereas Observable return all the value and print 1, 2, 3 in the console.

Promise is not lazy while Observable is lazy. Observable is lazy in nature and do not return any value until we subscribe.

home.component.ts (Observable)

In above example we are not subscribing the observable, so we do not receive the data and even there would be a no network call for this service.

home.component.ts (Observable)

Here, we have subscribed our Observable, so it will simply return the data. But Promise returns the value regardless of then() method.

home.component.ts (Promise)

Observable is cancellable in nature by invoking unsubscribe() method, but Promise is not cancellable in nature.

A good introduction connecting the concepts of Observables can be found in this article.

Hope this is helpful and gives you a basic understanding of how Promise differs from Observable. Please feel free to provide your suggestions 🙂


References:

http://csharp-video-tutorials.blogspot.com/2017/09/angular-promises-vs-observables.html
https://medium.com/@mpodlasin/promises-vs-observables-4c123c51fe13

knoldus-advt-sticker

3 thoughts on “Promise vs Observable in Angular2 min read

  1. Nice straight forward explanation of the difference between the 2. I would add that Observable has access to useful operators like map and forEach among others.

  2. Good post.please explain more this “Yes, Observable can handle multiple responses for the same request”
    Thanks

Comments are closed.

%d bloggers like this: