Following are the main building blocks of an Angular application. You can see them in the following picture:

20) What is the difference between Observables and Promises in Angular?
In Angular, as soon as we make a promise, the execution takes place, but this is not the case with observables because they are lazy. It means nothing happens until a subscription is made.
Promise | Observable |
---|
It emits a single value. | It emits multiple values over a period of time. |
Not Lazy | Lazy. An observable is not called until we subscribe to the observable. |
We can not cancel it. | We can cancel it by using the unsubscribe() method. |
| Observable provides operators like map, forEach, filter, reduce, retry, retryWhen etc. |
Let's understand it by an example:
- const observable = rxjs.Observable.create(observer => {
- console.log('This is what inside an observable');
- observer.next('Hello madAnswer');
- observer.complete();
- });
- console.log('Before subscribing an Observable');
- observable.subscribe((message)=> console.log(message));
When you run the above Observable, you can see the following messages displayed in the following order:
- Before subscribing an Observable
- This is what inside an observable
- Hello Madanswer
Here, you can see that observables are lazy. Observable runs only when someone subscribes to them. That's why the message "Before subscribing an Observable" is displayed ahead of the message inside the observable.
Now see the example of a Promise:
- const promise = new Promise((resolve, reject) => {
- console.log('This is what written inside promise');
- resolve('Hello madanswer');
- });
- console.log('Before calling then method on Promise');
- greetingPoster.then(message => console.log(message));
When you run the above Promise, you will see the messages displayed in the following order:
- This is what written inside Promise
- Before calling then method on Promise
- Hello Madanswer
Here, you can see that the message inside Promise is displayed first. This means that the Promise runs first, and then the method is called.
The next difference between them is that Promises are always asynchronous; even when the Promise is immediately resolved. On the other hand, an Observable can be both synchronous and asynchronous.
In the case of the above example, observable is synchronous. Let's see the case where an observable can be asynchronous:
- const observable = rxjs.Observable.create(observer => {
- setTimeout(()=>{
- observer.next('Hello madanswer');
- observer.complete();
- },3000)
- });
- console.log('Before calling subscribe on an Observable');
- observable.subscribe((data)=> console.log(data));
- console.log('After calling subscribe on an Observable');
When you run the above observable, you will see the messages in the following order:
- Before calling subscribe on an Observable
- After calling subscribe on an Observable
- Hello madanswer