One painful thing when working with Angular is getting used to Observables vs Promises, and how some libraries use one or the other exclusively. It can be incredibly frustrating to add a library only to find it wants to force you into using promises, when the rest of your project uses observables.
But why would you use one or the other? Well…
You generally use an Observable if :
- You are building something entirely for Angular as most of Angular uses Observables, it’s nice to keep to the same script.
- You need to output more than one value over time/stream data, observables allow you to output multiple values while a promise can only output one.
- You want to use RxJS operators such as map, tap etc.
You generally use a Promise if :
- You are only ever going to return a single value
- You prefer the “await” construct over using “then” or “subscribe”
In will get a feel over time as to which one you will need to use, but if you are using Angular, then chances are you will be sticking with Observables.
The real challenge comes when you have a library that will only return promises/observables, and your code is written completely the other way. Well never fear!
Turning Promises Into Observables
Converting a promise into an observable is rather easy with the “from” operator.
First, import “from” from the rxjs library :
import { from } from 'rxjs';
Then it’s as easy as :
from(myService.myPromiseMethod()).subscribe(x => console.log(x));
Be very careful that you use the “from” operator and not “of”. For example :
of(myService.myPromiseMethod())
This will return an observable but the value will be the promise itself, not the returned value of the promise. of is a really useful operator to return synchronous values inside your code, but should not be used for “unwrapping” promises.
Turning Observables Into Promises
If you thought going from a promise to an observable was easy, converting an observable into a promise is actually extremely easy with the “toPromise()” method available on every observable.
let myValue = await myService.getAll().toPromise();
There really isn’t much magic to it at all!
💬 Leave a comment