What is the difference between Promise
and Observable
in Angular?
An example on each would be helpful in understanding both the cases. In w
The basic difference between observable and promises are:
While the accepted answer is good in general I don't think it emphasises that when dealing with Angular Components you almost always want to use an Observable because it supports cancelation. Promises cannot be cancelled and will resolve even if your component is destroyed. Angular tends to be forgiving until it's not.
For example any manual change detection on a destroyed component will cause an exception:
ngOnInit() {
// promise api
this.service.getData().then(d => {
this.data = d;
this.changeDetectorRef.detectChanges();
});
// observable api
this.service.getData().pipe(takeUntil(this.unsubscribe)).subscribe((d) => {
this.data = d;
this.changeDetectorRef.detectChanges();
});
}
If your component is destroyed before the promise is resolved, you'll get an attempt to use destroyed view
error when the promise is resolved.
Alternatively, if you use observables with the takeUntil pattern, then as soon as your component is destroyed the subscription will be cancelled.
This is a bit of a contrived example but executing code for a component that is destroyed is probably going to lead to bugs. Unless you actually want to do that for some reason :p
Promises are focused only for single values or resolves, observables are stream of data.
Observables can be canceled but promises can't be canceled.
The least known one, atleast to me is
Promise
A Promise handles a single event when an async operation completes or fails.
Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far.
Observable
An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event.
Something I ran into that wasn't apparent from a first reading of the tutorial and docs was the idea of multicasting.
Make sure you're aware that by default, multiple subscriptions will trigger multiple executions in an Observable. Multiple subscriptions to a single HTTP call Observable will trigger multiple identical HTTP calls unless you .share()
(enable multicasting).
A promise forces you to deal with one thing at a time, unwrap its data, handle exceptions, has language support for cool things like async/await, and is pretty barebones otherwise.
An Observable has lots of bells and whistles, but you need to understand the power you're working with or it can be misused.