Updated April 17, 2023
Difference Between Angular Observable vs Promise
The following article provides an outline for Angular Observable vs Promise. In any Angular application, a dynamic and fast response is a key requirement which in turn requires a developer to handle multiple external service calls asynchronously, which is used widely within complex Angular applications. To achieve all this, Angular came up with a concept of Observables and Promise, where Promises was something used since AngularJS versions (1st version) as well and as an enhancement to promises with much more add ons are found in observables.
Head to Head Comparison Between Angular Observable vs Promise (Infographics)
Below are the top 5 differences between Angular Observable vs Promise:
Key Difference Between Angular Observable vs Promise
Let us discuss some of the major key differences between Angular Observable vs Promise:
- Using Angular Observables and Angular Promises, both are equally important, but Observables takes higher priority over Promises whenever Multiple asynchronous calls are present in an Angular Application. There are a couple of differences between Angular Observables and Promises, which are worth knowing as they will help us know where to use what.
- One of the major difference between Angular Observables and Angular Promises is that Observables follow a process of loading lazily which means they won’t be called in an application until they have been subscriber, on the other hand, Promises gets invoked as soon as they are created in an application, no matter if the execution is required or not.
- Angular Observables: Whenever we want to create a new Observable, we need to use the new keyword followed by Observable. The Observable function accepts a single parameter which is Data. To this Observable Function we call .subscribe function.
- Let’s take a look at the example below. There are also powerful operators like retry(), or replay(), forEach() that are often quite handy with Observables and widely used in Angular applications.
Example:
Code:
const dataFromObservable = new Observable((item) => {
item.next(10);
Item.next(20);
Item.next(30);
}).subscribe(response => console.log(‘ Response from Observable : ‘ + response));
Output :
Response from Observable: 10
Response from Observable: 20
Response from Observable: 30
- In the above code, we have created a new Observable, which has an item parameter, and we are invoking its .next operation and passing input value, i.e. 10, 20, 30. Now to this newly created Observable, we subscribe using the .subscribe method, and once it’s executed, console.log statement is printed Response from Observable. Now we can see that in output, we have 3 responses as observables processes multiple values at a time.
- Handling errors in Observable, the errors encountered during executions are delivered to the subscriber’s error handler, and the subscriber automatically unsubscribes from the observable.
Example:
Code:
observable.subscribe(() => {
throw new Error(‘ Generic Error’);
});
- Unsubscribing using Observables, where the processing of event can be cancelled using observable’s .unsubscribe() method.
Example:
Code:
const dataFromObservable = new Observable((item) => {
item.next(10);
Item.next(20);
Item.next(30);
}).subscribe(response => console.log(‘ Response from Observable : ‘ + response));
dataFromObservable.unsubscribe();
- Angular Promises: Whenever we want to create a new Promise which will call an external HTTP service and return a single response, we need to use the new keyword followed by Promise. The Promise function also accepts a single parameter which is Data. To this Promise Function, we can only call .then function.
Example:
Code:
const dataFromPromise = new Promise((item) => {
item(10);
item(20);
item(30);
}).then(response => console.log(‘ Response from Promise : ‘ + response));
Output:
Response from Promise: 10
- In the above code, we have created a new Promise which has an item parameter, and we are invoking it by passing input value, i.e. 10, 20, 30. Now to this newly created Promise we call invoke .then, and once its executed, console.log statement is printed Response from Promise.
- In the above code, we can see that only Response from Promise: 10 is returned as only the first value is read, and the rest are ignored. This is a major difference between Observable and Promise, where multiple values can be processed over a period of time in Observable, and a single value is processed using Promise.
- Handling errors in Promises, the errors encountered during executions are delivered to the child Promises.
Example:
Code:
promise.then(() => {
throw new Error(‘ Promise Error ‘);
});
Angular Observable vs Promise Comparison Table
Let’s discuss the top comparison between Angular Observable vs Promise:
Basis of Comparison | Angular Observable | Angular Promise |
Loading | This means that observables do not start execution until they have been subscribed. This makes Observables useful as we can run whenever we need the response. | Promises do not have Lazy Loading. This means Promises are executed as soon as they are created. |
Values | Observables can be used to emit multiple values over a period of time. Useful to fetch multiple values at a time. | Promises emit a single value at a time. |
Error Handling | Angular Observables are themselves responsible for handling errors. This way, all error handling can be done in a single place when we use Observables. | Angular Promises always push the error to the child promises instead of handling it themselves. |
Cancellation | Using the unsubscribe method. Observables can be cancelled whenever you need to stop listening from the receiving the values. | Promises can never be cancelled and will always be executed. |
Operations | Observables can have chaining and subscriptions. For example: forEach, filter, reduce, etc. operators can be used with observables. | Promise only support .then function. |
Conclusion
Angular Observables and Promises are widely used while building an Angular application. Creating new Angular Observables associated with a view and creating such multiple smaller Observables helps in code segregation, improves readability, and maintains code re-usability. On the other hand, Angular Promises add or modify the existing DOM behaviour and handle various events such as click, blur, focus, scroll, etc., and appropriate action can be taken in the Promises file. Knowing what to use when is all that you need to start with building Angular apps and using Angular Promises or Observables.
Recommended Articles
This is a guide to Angular Observable vs Promise. Here we discuss key differences with infographics and comparison table, respectively. You may also have a look at the following articles to learn more –