How to convert Promise to Observable in Angular?
Angular is a popular JavaScript framework for building web applications. Angular makes heavy use of Observables and Promises to manage asynchronous data streams.
The Observable is a type of data stream that can be used to represent the events emitted by an object that have been observed over time. An Observable can be created using the RxJs library and then subscribed to using the Observer pattern.
Observables are similar in appearance to Promises, but they are not the same thing. A Promise represents a single event whereas an Observable represents a stream of events that may come in any order or at any time.
What is Observable?
An Observable is a Producer of numerous values that “push” them to Observers (Consumers). On invocation, a Function is a lazily evaluated function that synchronously returns a single value.
What is a Promise?
As per the MDN
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value
The difference between Promise
and Observable
is that Promises can be resolved with a single value or an array of values, and Observables emit one or more values over time.
Angular by default returns Obserable
when you invoked HTTP client methods. But let’s assume that you have a function that returns a promise. In this case, you can easily change the return type from Promise
to Observable
. Converting promise
to Observable
is very straightforward in Angular. In order to do this first import from
operator from ’rxjs
and wrap the promise in the from the operator.
import { from } from 'rxjs';
const observable = from(promise);
It is possible to convert an observable into a promise by calling .toPromise().