Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Convert Observable to Promise

Q) How do I convert the following observable to a promise so I can call it with .then(...)?

My method I want to convert to a promise:

  this._APIService.getAssetTypes().subscribe(     assettypes => {         this._LocalStorageService.setAssetTypes(assettypes);     },     err => {         this._LogService.error(JSON.stringify(err))     },     () => {}   );  

The service method it calls:

  getAssetTypes() {     var method = "assettype";     var url = this.apiBaseUrl + method;      return this._http.get(url, {})       .map(res => <AssetType[]>res.json())       .map((assettypes) => {         assettypes.forEach((assettypes) => {           // do anything here you might need....       });       return assettypes;     });         }   

Thanks!

like image 710
Dave Avatar asked Apr 21 '16 18:04

Dave


People also ask

Can we convert Observable into Promise?

How to Convert an Observable to a Promise in Angular? Since the get method of HttpClient returns an observable, we use the toPromise() method to convert the observable to a promise. Since you can convert an observable to a promise, you can make use of the async/await syntax in your Angular code.

Which is better Promise or Observable?

The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.

Is toPromise deprecated?

but toPromise() is deprecated in recent versions of angular / rxjs.


1 Answers

rxjs7

lastValueFrom(of('foo')); 

https://indepth.dev/posts/1287/rxjs-heads-up-topromise-is-being-deprecated

rxjs6

https://github.com/ReactiveX/rxjs/issues/2868#issuecomment-360633707

Don't pipe. It's on the Observable object by default.

Observable.of('foo').toPromise(); // this 

rxjs5

import 'rxjs/add/operator/toPromise'; import 'rxjs/add/operator/map';  ...  this._APIService.getAssetTypes() .map(assettypes => {   this._LocalStorageService.setAssetTypes(assettypes); }) .toPromise() .catch(err => {   this._LogService.error(JSON.stringify(err)); }); 
like image 64
Günter Zöchbauer Avatar answered Oct 11 '22 15:10

Günter Zöchbauer