{

How to convert Observable to Promise in angular|Typescript


Sometimes, We want to convert observable to promise object and call callback then() on the promise in Angular. Observable returns multiple values and promise return single values.

Observable is feature-rich than promises and recommended. However, some cases need to convert to promises.

  • You have to pass data to a third party API that accepts only promises

How to Convert Observable to Promise in Angular

There are multiple ways we can do

  • use the toPromise method

Observable has the toPromise() method that subscribes to observable and returns the promise.

Note: Please make sure that the observable should complete the operation, Otherwise, It struck forever and causes memory errors.

Here is an syntax

Observable.toPromise()
      .then();

Here is a complete example to convert to promise in Angular.

import { Component } from '@angular/core';
import { delay, Observable, of } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  private myarray: string[] = ["test", "test2", "test3"]
  strings$: Observable<string[]> = of(this.myarray);
  array1$: Observable<string[]> = of(this.myarray).pipe(delay(5000));

  constructor() {
    console.log("start")

    const example = this.array1$.toPromise()
      .then(item => {
        console.log('Returned Promise value:', item);
      });

    console.log("end")
  }

}

Output:

start
end
Returned Promise value: (3)['test', 'test2', 'test3']

toPromise() is deprecated in rxjs7 version.

Rxjs provides lastValueFrom and firstValueFrom methods to convert promise.

lastValueFrom() used in place of toPromise() that return the stream of data

  public async getPromiseUseLast() {
    const promiseVar = await lastValueFrom(this.array1$);
    console.log('Returned lastValueFrom usage value:', promiseVar);

    return promiseVar;
  }

firstValueFrom() does not consider a stream of data, takes first data, and unsubscribes from the stream.

public async getPromiseUseFirst() {
  const promiseVar = await firstValueFrom(this.array1$);
  console.log('Returned firstValueFrom usage value:', promiseVar);

  return promiseVar;
}

Conclusion

In a summary,

Observable is more advanced and feature-rich than a promise, Some times need to convert promise into Angular.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.