How to Convert Promise to Observable in Angular

To convert Promise to Observable in Angular, you can “use the from() function from the rxjs library.”

To work with the rxjs library, you need to install it first if you have not installed it!

npm install rxjs --save

Promise to Observable in Angular

Import the rxjs library like this:

import { from } from 'rxjs';

Use the from() function to convert a promise to an observable:

import { from } from 'rxjs'

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Promise resolved');
  }, 2000);
});

const myObservable = from(myPromise);

myObservable.subscribe({
  next: (v) => console.log(v),
  error: (e) => console.error(e),
  complete: () => console.info('complete')
});

Output

Use the from() function to convert a promise to an observable

When the promise resolves, the Observable will emit the data and the subscriber’s callback will be executed.

Note that a Promise will be completed once resolved or rejected, meaning the Observable converted from it will also be completed after emitting the value or error.

If you want to work with Observables that emit multiple values over time, you might want to consider other creation functions or operators from rxjs.