Dave Dave - 13 days ago 6
TypeScript Question

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!

Answer
import 'rxjs/operator/add/toPromise';
import 'rxjs/operator/add/map';

...

this._APIService.getAssetTypes()
.map(assettypes => {
  this._LocalStorageService.setAssetTypes(assettypes);
})
.toPromise()
.catch(err => {
  this._LogService.error(JSON.stringify(err));
});
Comments