What is the difference between Promise and Observable in Angular ?


Promise and Observable are abstraction mechanisms that control the asynchronous behavior of applications.

Promise

A Promise handles a single event when an async operation completes or fails.

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. Observable provides operators like map, forEach, reduce, … similar to an array. There are also powerful operators like retry(), or replay(), … that are often quite handy. A list of operators shipped with rxjs

Promise VS Observable ?

Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn’t matter if you want to handle 0, 1, or multiple events. You can use the same API in each case.

Observable also has the advantage over Promise to be cancellable. While a Promise starts immediately, an Observable only starts if you subscribe to it. This is why Observables are called lazy and Promise are eager !!!

Commentaires

  1. Pingback: (SOLVED) How to create Angular HttpInterceptor ? » JavaTuto

Laisser un commentaire