For dealing with adaptive data in Angular, we can choose either Promise or Observable. Both get and post methods of HTTP and HttpClient return Observable and it can be converted into Promise using toPromise() method. So, what’s the distinction when they’re both dealing with adaptive data?
What actually is the difference?
Promise generates a mono value, whereas Observable generates a variable. So, while addressing an HTTP request, Promise can only manage a single response for the same request; however, if there are numerous responses to the same request, we must use Observable. Yes, multiple responses to the same request can be handled by Observable.
Let’s implement this with an example.
Promise
const promise = new Promise((data) => { data(1); data(2); data(3); }) .then(element => console.log(‘Promise ‘ + element));
Output
Promise 1
Explore how to use Resolve -Promises in Angular 2. Resolve is a potent tool for optimizing the user experience when switching among pages in your app. When compared to extracting information within the component, it also makes the component’s code much neater.
Observable
const observable = new Observable((data) => { data.next(1); data.next(2); data.next(3); }).subscribe(element => console.log('Observable ' + element));
Output
Observable 1
Observable 2
Observable 3
So, in the above code snippet, I have created promises and observables of Promise and Observable type respectively. But, the promise returns the very first value and ignores the remaining values whereas Observable returns all the values and prints 1, 2, 3 in the console.
The promise is not lazy while Observable is lazy. Observables are lazy in nature and do not return any value until we subscribe.
home.component.ts (Observable)
getMenu() { this.homeService.getFoodItem(); } }
In the above example, we are not subscribing to the observable, so we do not receive the data and even there would be no network call for this service.
home.component.ts (Observable)
getMenu() { this.homeService.getFoodItem().subscribe((data => { this.foodItem = data; }), error => console.log(error)); } }
Here, we have subscribed to our Observable, so it will simply return the data. But Promise returns the value regardless of the then() method.
home.component.ts (Promise)
getMenu() { this.homeService.getFoodItem() .then((data) => { this.foodItem = data; }); }
Observable is cancellable in nature by invoking the unsubscribe() method, but Promise is not cancellable in nature.