Knoldus Blog Audio
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.
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.
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.
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.
Here, we have subscribed our Observable, so it will simply return the data. But Promise returns the value regardless of then() method.
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 🙂