What is the difference between promise and observable in Angular?
In Angular, both Promises and Observables are used to handle asynchronous data, but there are some key differences between the two:
- Completion: A Promise represents a single value that will be available at some point in the future, whereas an Observable represents a stream of values that can arrive over time and can be processed as they arrive.
- Lazy execution: Promises are eager, meaning that they start processing immediately when created, whereas Observables are lazy, meaning that they only start processing when subscribed to.
- Error handling: Promises will propagate errors through the
catch
method, whereas Observables will emit errors through theerror
observable. - Cancellation: It’s difficult to cancel a Promise once it’s in progress, whereas it’s easier to unsubscribe from an Observable to stop its processing.
- Multicast: Promises are unicast, meaning that they can only be consumed once, whereas Observables are multicast, meaning that they can be subscribed to by multiple subscribers.
Here’s an example of a Promise in Angular:
getData(): Promise<any> {
return this.http.get('https://api.example.com/data').toPromise();
}
ngOnInit() {
this.dataService.getData().then(data => {
this.data = data;
});
}
And here’s an equivalent example using an Observable:
getData(): Observable<any> {
return this.http.get('https://api.example.com/data');
}
ngOnInit() {
this.dataService.getData().subscribe(data => {
this.data = data;
});
}
In general, Promises are best suited for handling a single value, while Observables are better suited for handling a stream of values over time. However, you can use either Promises or Observables depending on your specific use case and the requirements of your application.