What is the difference between Promise
and Observable
in Angular?
An example on each would be helpful in understanding both the cases. In w
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