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!
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));
});
observable can be converted to promise like this:
let promise=observable.toPromise();
you dont really need to do this just do ...
import 'rxjs/add/operator/first';
this.esQueryService.getDocuments$.first().subscribe(() => {
event.enableButtonsCallback();
},
(err: any) => console.error(err)
);
this.getDocuments(query, false);
first() ensures the subscribe block is only called once (after which it will be as if you never subscribed), exactly the same as a promises then()